从 C++ std::vector 中删除元素

2021-12-21 00:00:00 vector c++

在迭代过程中从 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

相关文章