C++lambda从向量集中移除元素

C++ lambda remove elements from set of vectors

本文关键字:元素 集中 向量 C++lambda      更新时间:2023-10-16

我有以下集

    //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::vectorstd::list,在这些容器中,您可以通过复制单个元素来移除它们。但这对std::set()不起作用,因为std::remove_if()对集合的erase()方法一无所知,这是从集合中移除值的唯一方法。

您需要编写自己的代码来正确地迭代该集,并删除要删除的值。

注意最常见的陷阱:从集合中删除元素后,刚刚删除的迭代器将不再有效。