我可以在一行代码中将向量中与条件匹配的所有元素插入到集合中吗?
Can I insert into a set, all the elements of a vector that matches a condition, in a single line of code
我有一个元素向量。我想使用这个向量的元素来填充一个集合,这些元素与某个条件匹配。我可以使用一行或以比下面更简洁的方式执行此操作吗?
// 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); });
相关文章:
- 将二维数组的所有元素插入到一维数组中
- 如何将元素插入和迭代到这种映射.C++
- 无法在构造函数中执行设置元素插入
- 将数组的元素插入映射的时间复杂度是多少?
- 如何将元素插入到标准::地图的共享指针中?
- 如何将 n 个连续元素插入到元素类型不可复制的 std::vector 中?
- 将元素插入链接列表
- 创建一个函数以在给定位置将元素插入到列表中
- 我可以在一行代码中将向量中与条件匹配的所有元素插入到集合中吗?
- 为什么我不能将元素插入数组中的列表?
- 将多个偏移量的多个元素插入到一个矢量中
- 将元素插入排序数组
- 使用算法中的插入函数将元素插入空容器中,未给出预期的结果
- 使用动态分配创建数组并将元素插入其中
- 将元素插入字符串集 c++ 的向量中
- 如何将元素插入独特指针的多维矢量中
- 通过引用同一向量的元素插入到向量中
- 如何将元素插入 BST
- 如何将元素插入矢量的开头
- STL和元素插入中列表的动态分配