Vector Iterators Incompatible

后端 未结 10 935
别那么骄傲
别那么骄傲 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:37

    Your getVec() function returns a deep copy of the member vector, so the two getVec() calls you make to retrieve iterators get iterators to different containers. That is, you can't reach getVec().end() from a separate getVec().begin() iterator without invoking undefined behavior.

    You can solve this in two ways:

    1) Have getVec return a const reference (that is, const std::vector&) (preferred) or...

    2) Replace the two getVec() calls with one and save the result to a std::vector variable. Then, use that variable for both calls to begin() and end(). E.g:

    std::vector<int> v = myFoo.getVec();
    std::vector<int>::const_iterator b = v.begin();
    std::vector<int>::const_iterator e = v.end();
    
    0 讨论(0)
  • 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<int> :

    const std::vector<int> & 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<int> myCopy = myFoo.getVec();
    std::vector<int>::const_iterator i = myCopy.begin();
    while(i != myCopy.end())
    {
      //do stuff
      ++i;
    }
    

    Also +1 for not using namespace std;

    0 讨论(0)
  • 2020-12-05 00:49

    Another cause of the MSVC STL debug assertion "vector iterators incompatible" is operating on an invalidated iterator.

    I.e. v.erase(i), and then compare i != v.end() the erase invalidates i and so it cannot be used in a comparison.

    0 讨论(0)
  • 2020-12-05 00:49

    The problem is that you always return another copy of the vector. Use a reference:

    const std::vector<int>& getVec(){return myVec;} //other stuff omitted
    
    0 讨论(0)
提交回复
热议问题