从C ++ std :: vector中删除元素 [英] Removing elements from C++ std::vector

查看:240
本文介绍了从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;
  }
}

当编译时:

I'm getting the following error when compiling:


RoutingProtocolImpl.cc:368: error: argument of type bool (RoutingProtocolImpl::)(RoutingProtocolImpl::dv_entry*)' does not matchbool (RoutingProtocolImpl::*)(RoutingProtocolImpl::dv_entry*)'

对不起,我是一个C ++ newb。

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中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆