我有一个带有 std::vector 数据成员的类,例如
class foo{
public:
const std::vector<int> getVec(){return myVec;} //other stuff omitted
private:
std::vector<int> myVec;
};
现在,在我的主代码的某些部分,我尝试像这样迭代向量:
std::vector<int>::const_iterator i = myFoo.getVec().begin();
while( i != myFoo.getVec().end())
{
//do stuff
++i;
}
当我到达这个循环时,我收到了上述错误。
您得到此信息的原因是迭代器来自 myVec 的两个(或更多)不同副本。每次调用时都会返回向量的副本myFoo.getVec()
。所以迭代器是不相容.
一些解决方案:
返回一个 const 引用std::vector<int>
:
const std::vector<int> & getVec(){return myVec;} //other stuff omitted
另一个解决方案,可能更好的是获取向量的本地副本并使用它来获取迭代器:
const std::vector<int> myCopy = myFoo.getVec();
std::vector<int>::const_iterator i = myCopy.begin();
while(i != myCopy.end())
{
//do stuff
++i;
}
也+1表示不using namespace std;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)