使用条件迭代器插入向量 [英] Insert into vector with conditional iterator

查看:124
本文介绍了使用条件迭代器插入向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个带有各种条目的向量,我希望将其插入到另一个向量中,同时省略满足条件的条目。

Say I have a vector with various entries, which I want to insert into another vector, while leaving out entries that satisfy a condition.

例如,我想插入一个向量,同时省略所有三个。

For example, I want to insert a vector while leaving out all three's.

{1, 3, 2, 3, 4, 5, 3} -> { /* previous content, */ 1, 2, 4, 5}

我想出了什么到目前为止使用 std :: partition ,它不保留相对顺序并重新排列源向量。

What I came up with so far uses std::partition, which does not preserve the relative order and rearranges the source vector.

std::vector<int> source({1, 3, 2, 3, 4, 5, 3});
std::vector<int> target;

auto partition = std::partition(std::begin(source),
                   std::end(source), [](const auto& a) { return a == 3; });
target.insert(std::begin(target), partition, std::end(source));

我在寻找什么更像是一个检查条件的迭代器如果条件不满意,继续前进。这样的事情:

What I am looking for is more of an iterator that checks a condition and moves on if the condition is not satisfied. Something like this:

target.insert(std::begin(target),
              conditional_begin(source, [](const auto& a) { return a != 3; },
              conditional_end(source));

我想有一个 conditional_end 函数是必要的,因为 std :: end 会返回不同的迭代器类型比 conditional_begin

I suppose a conditional_end function would be necessary, since std::end would return a different iterator type than conditional_begin.

也许我忽略了一些东西,所以我的问题是:

Maybe I have overlooked something, so my questions are:


  • 标准库是否提供类似的东西?

  • 是否有不同的简单方法来实现我的目标?

  • 有没有一种简单的方法来实现条件迭代器功能?

推荐答案


有没有不同的简单方法来实现我的目标?

Is there a different easy way to achieve my goal?

是的,标准已经内置了这个功能。你的功能是l ooking for std :: copy_if

Yes, the standard already has this functionality built in. The function you are looking for is std::copy_if.

std::vector<int> source({1, 3, 2, 3, 4, 5, 3});
std::vector<int> target;

std::copy_if(source.begin(), 
             source.end(), 
             std::back_inserter(target), [](auto val){ return val != 3; });

此处, std :: back_inserter(target),将在 target 上为谓词返回的每个元素调用 push_back true

Here, std::back_inserter(target), will call push_back on target for each element that the predicate returns true.

这篇关于使用条件迭代器插入向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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