我可以在一行代码中将向量中与条件匹配的所有元素插入到集合中吗?

Can I insert into a set, all the elements of a vector that matches a condition, in a single line of code

本文关键字:元素 插入 集合 一行 我可以 向量 代码 条件      更新时间:2023-10-16

我有一个元素向量。我想使用这个向量的元素来填充一个集合,这些元素与某个条件匹配。我可以使用一行或以比下面更简洁的方式执行此操作吗?

// given vector<int> v
set<int> s;
for (const int& i : v)
{
    if (/* some condition on i*/)
        s.insert(i);
}

例如,类似于以下内容的内容:

// given vector<int> v
set<int> s;
s.insert(v.filter(/* lambda here*/));

不言而喻,出于性能原因,v.filter 方法应该返回一个迭代器,而不是一个单独的填充向量。

您可以将std::copy_if与 lambda 和 std::inserter 一起使用,将值插入到集合中。 那看起来像

std::copy_if(v.begin(), v.end(), std::inserter(s, s.begin()), [](auto val) { return val == some_condition; });

使用 range-v3,它将是

set<int> s = v | ranges::view::filter([](int e){ return cond(e); });

或者只是(如果cond已经存在(

set<int> s = v | ranges::view::filter(cond);

+1 表示std::copy_if()解决方案,恕我直言,这是此问题的自然解决方案。

只是为了好玩,我提出了一个基于std::for_each()的不同解决方案

std::set<int> s;
std::for_each(v.cbegin(), v.cend(),
              [&](int i) { if ( /* some condition */ ) s.insert(i); });