我想在对象数组上构造嵌套循环,具有相当复杂的数据结构。因为我使用数组,所以我想利用它们的迭代器。在得到意想不到的结果后,我将问题归结为以下代码片段,当我期望迭代器不同时,它显示我的迭代器是相等的:
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;
这会产生:
The beginnings of the vectors are different: 0
0
0
But the iterators are equal: 1
这种行为对我来说没有意义,我很乐意听到解释。
Foo 是一个简单的对象,其中包含一个向量和 getter 函数:
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;
}
当第一次复制向量时,问题就消失了。为什么?
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;
产生:
The beginnings of the vectors are different: 0
And now also the iterators are different: 0
进一步说明:我需要函数中的这些嵌套循环,这些循环需要在计算时间方面非常有效,因此我不想做不必要的操作。由于我是 C++ 新手,我不知道复制向量是否真的需要额外的时间,或者它们是否会在内部被复制。我也感谢任何其他建议。