STL向量迭代器不兼容

STL向量迭代器不兼容

本文介绍了C ++ STL向量迭代器不兼容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// 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;
    }
}

此部分用于擦除FDRFreq矢量项,其中数据长度小于标准数,但调试断言失败:向量迭代器不兼容。

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. I am a green hand in C++ STL, thanks for your kindly help.

推荐答案

您的代码需要成为

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

向量迭代器不兼容重新使用已被无效 - 也就是说,不能保证它指向的元素仍然存在于该存储器位置。向量元素的擦除使该位置之后的迭代器无效。 .erase 返回一个新的,有效的迭代器,您可以改用。

"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.

如果你刚接触STL,强烈建议您阅读Scott Myer的有效STL (以及 Effective C ++

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

这篇关于C ++ STL向量迭代器不兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 03:19