Vector Iterators Incompatible

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

    Another reason why this assert can trigger is if you would allocate "foo" with 'malloc' instead of 'new', effectively skipping the constructor(s).

    It's unlikely to happen to a project developed from scratch in C++, but when converting plain-C code to C++ (replacing a static array[] in some struct with an stl-vector) you might just not realise that dynamic instances of said struct (and the members inside) are not going to have their constructor called - unless you also change 'malloc' to 'new'.

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

    You are returning a copy of the vector. Because you are returning by value - your call to begin() and end() are for completely different vectors. You need to return a const & to it.

    const std::vector<int> &getVec(){return myVec;}
    

    I would do this slightly differently though. I'd make the class act a little like a standard container

    class Data
    {
       public:
          typedef std::vector<int>::const_iterator const_iterator;
    
          const_iterator begin() const { return myVec.begin(); }
          const_iterator end() const { return myVec.end(); }
    };
    
    Data::const_iterator i=myFoo.begin();
    
    while(i != myFoo.end())
    {
    //
    }
    
    0 讨论(0)
  • 2020-12-05 00:30

    Change

    const std::vector<int> getVec(){return myVec;}
    

    to

    const std::vector<int>& getVec(){return myVec;}
    
    0 讨论(0)
  • 2020-12-05 00:32

    well, I don't think vector copy could be the only cause, that seems to be too obivious to me.

    in my case I just find that corrupted stack, heap, uninteneded changes could also result in this failure, and it will in fact hiding the underlying reason. in my case, I changed to use indexer to iterate through and find the root cause.

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

    Because you are returning by value - your call to begin() and end() are for completely different vectors. You need to return a const & to it

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

    You are making a constant copy of the member vector, not accessing the member vector.

    Change this:

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

    to this:

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

    To go a little deeper, the iterator you get from this statement:

    std::vector<int>::const_iterator i = myFoo.getVec().begin();
    

    is an iterator to the temporary copy of your vector, which goes away after that statement executes, invalidating the iterator.

    0 讨论(0)
提交回复
热议问题