C++lambda从向量集中移除元素
C++ lambda remove elements from set of vectors
我有以下集
//Create a set which orders the elements according to their size.
auto comp = [](const vector<int>& a, const vector<int>& b) -> bool
{
if (a.size() < b.size())
return true;
if (a.size() > b.size())
return false;
return a < b;
};
auto path = std::set <vector<int>, decltype(comp)> (comp);
以及以下矢量。
vector<int> nodePath;
并且我想要移除集合中大小大于nodePath向量大小的所有元素。
path.erase(std::remove_if(path.begin(), path.end(),
[](vector<int> task) { return task.size()>nodePath.size(); }), path.end());
当我执行这样的程序时,他抛出:
main.cpp: In lambda function:
main.cpp:347:93: error: ‘nodePath’ is not captured
[](vector<int> task) { return task.size()>nodePath.size(); }), path.end());
^~~~~~~~
main.cpp:347:52: note: the lambda has no capture-default
[](vector<int> task) { return task.size()>nodePath.size(); }), path.end());
^
main.cpp:285:29: note: ‘std::vector<int> nodePath’ declared here
vector<int> nodePath;
如果我把nodePath向量放在[]中,他会抛出:
In file included from /usr/include/c++/6.1.1/algorithm:62:0,
from main.cpp:7:
/usr/include/c++/6.1.1/bits/stl_algo.h: In instantiation of ‘_ForwardIterator std::__remove_if(_ForwardIterator, _ForwardIterator, _Predicate) [with _ForwardIterator = std::_Rb_tree_const_iterator<std::vector<int> >; _Predicate = __gnu_cxx::__ops::_Iter_pred<run(int*, char***)::<lambda(std::vector<int>)> >]’:
/usr/include/c++/6.1.1/bits/stl_algo.h:936:30: required from ‘_FIter std::remove_if(_FIter, _FIter, _Predicate) [with _FIter = std::_Rb_tree_const_iterator<std::vector<int> >; _Predicate = run(int*, char***)::<lambda(std::vector<int>)>]’
main.cpp:347:119: required from here
/usr/include/c++/6.1.1/bits/stl_algo.h:868:16: error: passing ‘const std::vector<int>’ as ‘this’ argument discards qualifiers [-fpermissive]
*__result = _GLIBCXX_MOVE(*__first);
std::remove_if()
不能与集合一起使用。
从集合中移除值的唯一方法是使用其erase()
方法。
std::remove_if()
从序列中删除值,方法是从字面上复制值,并返回新序列的结束迭代器值。您确实使用结束迭代器值调用了erase()
,但这还不够。
std::remove_if()
用于序列容器,如std::vector
或std::list
,在这些容器中,您可以通过复制单个元素来移除它们。但这对std::set()
不起作用,因为std::remove_if()
对集合的erase()
方法一无所知,这是从集合中移除值的唯一方法。
您需要编写自己的代码来正确地迭代该集,并删除要删除的值。
注意最常见的陷阱:从集合中删除元素后,刚刚删除的迭代器将不再有效。
相关文章:
- 如何从存储在std::映射中的std::集中删除元素
- 在std::集中获取与给定元素最接近的元素
- 如何查看提升集中<cpp_int>的下一个和上一个元素
- 如何有效地从C++集中删除开始和结束元素
- 如何在 c++ 集中插入元素,直到按下 Enter 键
- 如何检查 O(N) 时间复杂度的多重集中是否有 2 个或更多元素具有相同的值
- 如何在C++中减少多集中元素的数量
- 指针集中元素的顺序
- 从C 中的2D集中删除元素
- 更改STL多集中两个相等元素的顺序
- 如何有效地从std::集中选择随机元素
- 如何遍历两对 STL 集中的所有元素<对<t1,t2>,pair<t1,t2>>?
- 多集是如何工作的,以及如何在多集中找到最小元素
- 如何使迭代器指向与C++集中的另一个元素相同的元素
- 获取C++多集中的前N个元素
- 将连字符作为元素包含在scanf()的扫描集中,如果它是列表中的第一个字符或最后一个字符
- 为什么我不能在 STL 集中插入 600 万个元素?
- 在并集中命名数组元素或结构和数组
- 如何将数组的元素分配给 x86 程序集中的变量
- C++lambda从向量集中移除元素