问题描述
我有一个类与std :: vector数据成员例如
I have a class with a std::vector data member e.g.
class foo{
public:
const std::vector<int> getVec(){return myVec;} //other stuff omitted
private:
std::vector<int> myVec;
};
现在在我的主要代码的某些部分,我试图遍历这样的向量: p>
Now at some part of my main code I am trying to iterate through the vector like this:
std::vector<int>::const_iterator i = myFoo.getVec().begin();
while( i != myFoo.getVec().end())
{
//do stuff
++i;
}
我到达这个循环的时候, >
The moment I reach this loop, I get the aforementioned error.
推荐答案
得到这个的原因是,迭代器来自两个(或更多)不同的myVec副本。您每次调用 myFoo.getVec()
时都返回一个向量的副本。因此,迭代器不兼容。
The reason you are getting this, is that the iterators are from two (or more) different copies of myVec. You are returning a copy of the vector with each call to myFoo.getVec()
. So the iterators are incompatible.
一些解决方案:
返回一个const引用到 std :: vector< int>
:
Return a const reference to the std::vector<int>
:
const std::vector<int> & getVec(){return myVec;} //other stuff omitted
$ b
Another solution, probably preferable would be to get a local copy of the vector and use this to get your iterators:
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;
这篇关于矢量迭代器不兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!