使用remove

编程入门 行业动态 更新时间:2024-10-16 16:43:40
本文介绍了使用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

本文发布于:2023-11-29 21:26:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647665.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:remove

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!