从 c++ 向量中移除元素,其中移除条件依赖于其他元素 [英] Remove elements from a c++ vector where the removal condition is dependent on other elements

查看:23
本文介绍了从 c++ 向量中移除元素,其中移除条件依赖于其他元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C++ 中从向量中删除某些元素的标准方法是删除/擦除习语.但是,传递给 remove_if 的谓词仅将考虑中的向量元素作为参数.如果谓词以数组的其他元素为条件,是否有一种很好的 STL 方法来做到这一点?

The standard way to remove certain elements from a vector in C++ is the remove/erase idiom. However, the predicate passed to remove_if only takes the vector element under consideration as an argument. Is there a good STL way to do this if the predicate is conditional on other elements of the array?

举一个具体的例子,考虑删除紧随其后的数字的所有重复项.这里移除第n个元素的条件是以第(n-1)个元素为条件的.

To give a concrete example, consider removing all duplicates of a number immediately following it. Here the condition for removing the n-th element is conditional on the (n-1)-th element.

之前:11234555111333
之后:1234513

Before: 11234555111333
After: 1234513

推荐答案

其他人已经提到了 std::unique,对于您的具体示例.Boost.Range 有 adjacent_filtered 适配器,它将范围中的当前元素和下一个元素传递给您的谓词,并且由于该谓词,它适用于更大范围的问题.然而,Boost.Range 也有 独特的适配器.

Others mentioned std::unique already, for your specific example. Boost.Range has the adjacent_filtered adaptor, which passes both the current and the next element in the range to your predicate and is, thanks to the predicate, applicable to a larger range of problems. Boost.Range however also has the uniqued adaptor.

另一种可能性是简单地保留对范围的引用,这在 C++11 中使用 lambda 很容易:

Another possibility would be to simply keep a reference to the range, which is easy to do with a lambda in C++11:

std::vector<T> v;
v.erase(std::remove_if(v.begin(), v.end(), 
    [&](T const& x){
      // use v, with std::find for example
    }), v.end());

这篇关于从 c++ 向量中移除元素,其中移除条件依赖于其他元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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