我想在对象数组上构造嵌套循环,具有相当复杂的数据结构。因为我使用数组,所以我想使用它们的迭代器。在我得到意想不到的结果后,我将问题归结为以下代码片段,它显示我的迭代器在我期望它们不同时是相等的:
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 是一个简单的对象,包含一个 vector 和它的 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 时,问题就消失了。为什么?
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++ 的新手,所以我不知道复制 vector 是否真的需要额外的时间,或者它们是否会在内部复制。我也感谢任何其他建议。
最佳答案
问题是您在 Foo 中的访问器:
std::vector<int> getMyIntVec() const {
return _myIntVec;
}
我不返回 _myIntVec,它返回 myIntVec 的拷贝。 相反,它应该看起来像:
const std::vector<int>& getMyIntVec() const {
return _myIntVec;
}
否则,当您创建迭代器时,它们是从直接丢弃的拷贝创建的,因此您的 C++ 编译器会重用该地址。这就是您获得“相等”迭代器的原因,至少我是这么认为的。
关于c++ - 嵌套迭代器循环,为什么迭代器相等? -C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16100865/