使用remove_if从C ++向量中删除索引 [英] Removing by index from a C++ vector using remove_if

查看:344
本文介绍了使用remove_if从C ++向量中删除索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以使用C ++中的remove_if在基于对元素进行操作的谓词的线性时间内从向量中删除元素。

  bool condition(double d){...} 

向量< double> data = ...
std :: remove_if(data.begin(),data.end(),condition);

如果我的条件不取决于值,而是取决于索引,该怎么办?换句话说,如果我想删除所有的奇数索引元素,或者某些任意索引集等等?

  bool condition (int index){//返回是否应删除该索引} 

vector< double> data = ...
std :: remove_if(data.begin(),data.end(),???);


解决方案

您可以使用指针运算找出 std :: remove_if 的特定元素传递给谓词:

  std :: remove_if(data.begin(),data.end(),
[](const double& d){return(& d - & * data.begin())%2); });请注意,remove_if传递了一个迭代器的解引用的结果,并且保证是一个<$ c $

c>引用
每个表106 - 标准中的迭代器要求。


We can use remove_if in C++ to remove elements from a vector in linear time based on a predicate that operates on the elements.

bool condition(double d) {...}

vector<double> data = ...
std::remove_if (data.begin(), data.end(), condition);

What if my condition depends not on the values, but on the indices? In other words, if I wanted to remove all the odd-indexed elements, or some arbitrary index set, etc?

bool condition(int index) {//returns whether this index should be removed}

vector<double> data = ...
std::remove_if (data.begin(), data.end(), ???);

解决方案

You can use pointer arithmetic to find the index of a specific element that std::remove_if passes to the predicate:

std::remove_if(data.begin(), data.end(),
               [](const double& d) { return (&d - &*data.begin()) % 2); });

Note that remove_if passes the result of dereferencing an iterator, and that's guaranteed to be a reference per Table 106 - Iterator requirements in the Standard.

这篇关于使用remove_if从C ++向量中删除索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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