矢量迭代器不兼容 [英] Vector Iterators Incompatible

查看:229
本文介绍了矢量迭代器不兼容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类与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;

这篇关于矢量迭代器不兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆