C++ STL vector iterators incompatible

后端 未结 2 1237
予麋鹿
予麋鹿 2020-12-21 22:41
// Erase the missing items
vector::size_type StandardNum = FDRFreq.at(0).fData.size();
vector::iterator iter = FDRFreq.be         


        
2条回答
  •  太阳男子
    2020-12-21 23:02

    Your code needs to become

    while (iter != FDRFreq.end()){
        if( iter->fData.size() < StandardNum){
            iter = FDRFreq.erase(iter);
        }
        else{
            ++iter;
        }
    }
    

    "vector iterators incompatible" means that the iterator you're using has been invalidated - that is to say, there is no guarantee that the elements it points to still exist at that memory location. An erase of a vector element invalidates the iterators following that location. .erase returns a new, valid iterator you can use instead.

    If you're new to STL, I highly recommend you read Scott Myer's Effective STL (and Effective C++, while you're at it)

提交回复
热议问题