简体   繁体   English

C ++ STL向量迭代器不兼容

[英]C++ STL vector iterators incompatible

// Erase the missing items
vector<AlignedFDRData>::size_type StandardNum = FDRFreq.at(0).fData.size();
vector<AlignedFDRData>::iterator iter = FDRFreq.begin(); 
while (iter != FDRFreq.end()){
    if( iter->fData.size() < StandardNum){
        FDRFreq.erase(iter);
    }
    else{
        ++iter;
    }
}

This part is used to erase the FDRFreq vector item, in which the data length is smaller than the standard number, but the debug assertion failed: vector iterators incompatible. 此部分用于擦除FDRFreq向量项,其中的数据长度小于标准数字,但调试断言失败:向量迭代器不兼容。 I am a green hand in C++ STL, thanks for your kindly help. 我是C ++ STL的专家,感谢您的帮助。

Your problem is iterator invalidation after the call to std::erase . 您的问题是在调用std::erase之后迭代器无效。 The warning is triggered by an iterator debugging extensions in your standard library implementation. 该警告是由标准库实现中的迭代器调试扩展触发的。 erase returns an iterator to the new valid location after the erase element and you continue iterating from there. erase将迭代器返回到擦除元素之后的新有效位置,然后您从那里继续进行迭代。 However, this is still very inefficient. 但是,这仍然非常低效。

Use the Erase-Remove Idiom to remove data with a predicate from a vector . 使用Erase-Remove Idiomvector删除带有谓词的数据。

FDRFreq.erase(std::remove_if(
                begin(FDRFreq), end(FDRFreq), 
                [&StandardNum](const AlignedFDRData& x) { 
                  return fData.size() > StandardNum; }),
              end(FDRFreq));

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. .erase返回一个可以使用的新的有效迭代器。

If you're new to STL, I highly recommend you read Scott Myer's Effective STL (and Effective C++ , while you're at it) 如果您是STL的新手,我强烈建议您阅读Scott Myer的Effective STL (和Effective C ++ )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM