Removing elements from C++ std::vector(从 C++ std::vector 中删除元素)
问题描述
在迭代过程中从 C++ 向量中删除元素的正确方法是什么?我正在迭代一个数组并想删除一些匹配特定条件的元素.有人告诉我,在遍历期间修改它是一件坏事.
What is the proper way to remove elements from a C++ vector while iterating through it? I am iterating over an array and want to remove some elements that match a certain condition. I've been told that it's a bad thing to modify it during traversal.
我想我还应该提到这是一个指针数组,我需要在删除它们之前释放它们.
I guess I should also mention that this is an array of pointers that I need to free before removing them.
这是我的代码片段.
void RoutingProtocolImpl::removeAllInfinity()
{
  dv.erase(std::remove_if(dv.begin(), dv.end(), hasInfCost), dv.end()); 
}
bool RoutingProtocolImpl::hasInfCost(RoutingProtocolImpl::dv_entry *entry)
{
  if (entry->link_cost == INFINITY_COST)
  {
    free(entry);
    return true;
  }
  else
  {
    return false;
  }
}
编译时出现以下错误:
RoutingProtocolImpl.cc:368: error: argument of type bool (RoutingProtocolImpl::)(RoutingProtocolImpl::dv_entry*)' does not matchbool (RoutingProtocolImpl::)(RoutingProtocolImpl::dv_entry)'
抱歉,我是 C++ 新手.
Sorry, I'm kind of a C++ newb.
推荐答案
bool IsEven (int i) 
{ 
  return (i%2) == 0; 
}
//...
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.erase(std::remove_if(v.begin(),v.end(),IsEven), v.end()); 
//v now contains 1 and 3
                        这篇关于从 C++ std::vector 中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 C++ std::vector 中删除元素
				
        
 
            
        - Stroustrup 的 Simple_window.h 2022-01-01
 - 如何对自定义类的向量使用std::find()? 2022-11-07
 - STL 中有 dereference_iterator 吗? 2022-01-01
 - 静态初始化顺序失败 2022-01-01
 - C++ 协变模板 2021-01-01
 - 近似搜索的工作原理 2021-01-01
 - 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
 - 从python回调到c++的选项 2022-11-16
 - 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
 - 使用/clr 时出现 LNK2022 错误 2022-01-01
 
						
						
						
						
						
				
				
				
				