2011-03-07 105 views
5

我有几个元素组成的stl矢量。我需要遍历这个向量并删除符合某些条件的元素。所以我写了这个代码为什么我不能删除矢量的最后一个元素

此代码工作正常,几乎所有的情况,但是如果向量的所有元素符合标准,我得到一个错误:

vector erase iterator outside the range 

会出现此错误,如果我只有一个元素留在向量中。我做错了什么?

回答

11
if(imageDataVector[i] < threshold) 
     imageDataVector.erase(imageDataVector.end()-j); 

可能应:

if(imageDataVector[j] < threshold) 
     imageDataVector.erase(imageDataVector.begin()+j); 

编辑:对于完整性,擦除 - 删除的方式和迭代的方式:

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; 
} 
+0

ee是的,我的坏。现在它工作正常:) – igor 2011-03-07 21:07:44

+2

+1,重要的是要注意,* good *方式是* erase-remove *方式,因为它比其他方式更有效(特别是在所有元素相遇的最坏情况下标准* erase-remove *是线性* O(N)*,而另外两个版本具有二次性能* O(N^2)* – 2011-03-07 21:22:35

6

你混合向前和向后的索引。

我会考虑使用std::remove_if来代替。这样,如果您要删除多个元素,则不会在每次擦除时向前移动整个向量。

这将是这个样子:

imageDataVector.erase(std::remove_if(imageDataVector.begin(), imageDataVector.end(), std::bind2nd(std::less<data_type>(), threshold)), imageDataVector.end()); 

或者尝试以下方法,并指出这将导致大量的运动,如果你删除的矢量多个项目。

for (int j=imageDataVector.size()-1 ;j>=0;j--) 
{ 
    if(imageDataVector[i] < threshold) 
     imageDataVector.erase(imageDataVector.begin()+j); 
} 
+0

是否有可能用更多的std :: less <>奇特的功能??像c#中的比较器...... – igor 2011-03-07 22:39:37

+0

@igor你可以用任何接受一个参数的东西代替它,如果应该删除该项目,则返回true。 – 2011-03-07 23:08:02

3

你试着到j计数下降到零,而imageDataVector.end() - 0是不是一个有效的迭代。在标准的C++库容器中,end迭代器指向最后一个元素的后面,而不是最后一个元素。

相关问题