为什么我不能删除向量的最后一个元素 [英] Why can't I delete last element of vector
本文介绍了为什么我不能删除向量的最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有由几个元素组成的stl向量.我需要遍历此向量并删除符合某些条件的元素.所以我写了这段代码
I have stl vector consisting of several elements. I need to iterate through this vector and delete elements which meets some criteria. So I wrote this code
for (int j = imageDataVector.size()-1; j >= 0; j--) {
if(imageDataVector[i] < threshold)
imageDataVector.erase(imageDataVector.end() - j);
}
此代码几乎可以在所有情况下正常工作,但是,如果vector的所有元素都符合条件,则会报错:
This code works fine for almost all cases, however if all elements of vector meets the criteria I get an error:
vector erase iterator outside the range
如果向量中仅剩一个元素,则会发生此错误.我该怎么办?
This error occurs if I have only one element left in the vector. What do I do wrong ?
推荐答案
if(imageDataVector[i] < threshold)
imageDataVector.erase(imageDataVector.end()-j);
应该是:
if(imageDataVector[j] < threshold)
imageDataVector.erase(imageDataVector.begin()+j);
为完整起见,使用擦除删除方式和迭代器方式:
for completeness, the erase-remove way and the iterator way:
imageDataVector.erase(std::remove_if(imageDataVector.begin(), imageDataVector.end(), std::bind2nd(std::less<vector_data_type>(), threshold)), imageDataVector.end());
vector<type>::iterator it = imageDataVector.begin();
while (it != imageDataVector.end()) {
if (*it < threshold)
it = imageDataVector.erase(it);
else
++it;
}
这篇关于为什么我不能删除向量的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文