I want to construct nested loops over arrays of objects, having a rather complex data structure. Because I use arrays, I want to make use of their iterators. After I got unexpected results I boiled down the problem to the following code snippet, that shows my iterators to be equal when I expect them to be 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 the vectors are 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 the iterators are equal: "
<< (itA==itB) << endl;
This produces:
The beginnings of the vectors are different: 0
0
0
But the iterators are equal: 1
This behaviour does not make sense to me and I'd be happy about hearing an explanation.
Foo is a simple object containing a vector and getter function for 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 the vectors the 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 the vectors are different: "
<< (intVecReceiveA.begin() == intVecReceiveB.begin()) << endl;
cout << "And now also the iterators are different: "
<< (newItA==newItB) << endl;
produces:
The beginnings of the vectors are different: 0
And now also the iterators are different: 0
Further notes: I need these nested loops in functions which need to be extremely efficient regarding computation time, thus I would not want to do unnecessary operations. Since I'm new to c++ I do not know whether copying the vectors would actually take additional time or whether they would be copied internally anyway. I'm also thankful for any other advice.