arrays - nested iterator loop, why are iterators equal? - c++ -
i want construct nested loops on arrays of objects, having rather complex data structure. because use arrays, want make use of iterators. after got unexpected results boiled down problem following code snippet, shows iterators equal when expect them different:
vector<int> intveca; vector<int> intvecb; intveca.push_back(1); intveca.push_back(2); intvecb.push_back(5); intvecb.push_back(4); foo fooone(intveca); foo footwo(intvecb); vector<int>::const_iterator ita = fooone.getmyintvec().begin(); vector<int>::const_iterator itb = footwo.getmyintvec().begin(); cout << "the beginnings of vectors different: " << (fooone.getmyintvec().begin() == footwo.getmyintvec().begin()) << endl; cout << (*(fooone.getmyintvec().begin()) == *(footwo.getmyintvec().begin())) << endl; cout << (&(*(fooone.getmyintvec().begin())) == &(*(footwo.getmyintvec().begin()))) << endl; cout << "but iterators equal: " << (ita==itb) << endl; this produces:
the beginnings of vectors different: 0 0 0 iterators equal: 1 this behaviour not make sense me , i'd happy hearing explanation.
foo simple object containing vector , getter function it:
class foo { public: foo(std::vector<int> myintvec); std::vector<int> getmyintvec() const { return _myintvec; } private: std::vector<int> _myintvec; }; foo::foo(std::vector<int> myintvec) { _myintvec = myintvec; } when first copying vectors problem vanishes. why?
vector<int> intvecreceivea = fooone.getmyintvec(); vector<int> intvecreceiveb = footwo.getmyintvec(); vector<int>::const_iterator newita = intvecreceivea.begin(); vector<int>::const_iterator newitb = intvecreceiveb.begin(); cout << "the beginnings of vectors different: " << (intvecreceivea.begin() == intvecreceiveb.begin()) << endl; cout << "and iterators different: " << (newita==newitb) << endl; produces:
the beginnings of vectors different: 0 , iterators different: 0 further notes: need these nested loops in functions need extremely efficient regarding computation time, not want unnecessary operations. since i'm new c++ not know whether copying vectors take additional time or whether copied internally anyway. i'm thankful other advice.
the problem accessor in foo:
std::vector<int> getmyintvec() const { return _myintvec; } i doesn't return _myintvec, returns copy of myintvec. instead should like:
const std::vector<int>& getmyintvec() const { return _myintvec; } otherwise when create iterators created copies directly thrown away c++ compiler reuses address. why "equal" iterators, @ least think so.
Comments
Post a Comment