Vector Iterators Incompatible

后端 未结 10 1006
别那么骄傲
别那么骄傲 2020-12-04 23:54

I have a class with a std::vector data member e.g.

class foo{
public:

const std::vector getVec(){return myVec;} //other stuff omitted

private:
s         


        
10条回答
  •  死守一世寂寞
    2020-12-05 00:45

    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.

    Some solutions:

    Return a const reference to the std::vector :

    const std::vector & getVec(){return myVec;} //other stuff omitted
    

    Another solution, probably preferable would be to get a local copy of the vector and use this to get your iterators:

    const std::vector myCopy = myFoo.getVec();
    std::vector::const_iterator i = myCopy.begin();
    while(i != myCopy.end())
    {
      //do stuff
      ++i;
    }
    

    Also +1 for not using namespace std;

提交回复
热议问题