std :: remove_if中的const参数

Fra*_*101 7 c++ lambda stl list c++11

我要从对列表中删除元素.当我使用一对像

std::pair<const int, bool>

我收到以下编译错误:

在/usr/local/include/c++/6.1.0/utility:70:0中包含的文件中,

来自/usr/local/include/c++/6.1.0/algorithm:60,

来自main.cpp:1:

/usr/local/include/c++/6.1.0/bits/stl_pair.h:在'std :: pair <_T1,_T2>&std :: pair <_T1,_T2> :: operator =(std ::)的实例化中pair <_T1,_T2> &&)[with _T1 = const int; _T2 = bool]':

/usr/local/include/c++/6.1.0/bits/stl_algo.h:868:16:需要'_ForwardIterator std :: __ remove_if(_ForwardIterator,_ForwardIterator,_Predicate)[with _ForwardIterator = std :: _ List_iterator> _Predicate = __gnu_cxx :: __ ops :: _ Iter_pred&)>>]''

/usr/local/include/c++/6.1.0/bits/stl_algo.h:936:30:需要'_FIter std :: remove_if(_FIter,_FIter,_Predicate)[与_FIter = std :: _ List_iterator> _Predicate = main ()::&)>]"

main.cpp:17:32:从这里要求

/usr/local/include/c++/6.1.0/bits/stl_pair.h:319:8:错误:只读成员'std :: pair :: first'的分配

first = std :: forward(__ p.first);

这是示例代码:

int main()
{
    int id = 2;

    std::list< std::pair <const int, bool> >  l;
    l.push_back(std::make_pair(3,true));
    l.push_back(std::make_pair(2,false));
    l.push_back(std::make_pair(1,true));

    l.erase(std::remove_if(l.begin(), l.end(), 
        [id](std::pair<const int, bool>& e) -> bool {
        return e.first == id; }));

    for (auto i: l) {
        std::cout << i.first << " " << i.second << std::endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道(如果我错了,请纠正我):

  1. 只要列表的任何元素中存在constness,我就会遇到完全相同的问题,例如,a list <const int>也会返回编译错误.

  2. 如果我删除对中第一个元素中的const,代码将起作用.

  3. 更优雅和有效的方法是使用remove_if list方法,如下所示:

    l.remove_if([id](std::pair<const int, bool>& e) -> bool {
        return e.first == id; });
    
    Run Code Online (Sandbox Code Playgroud)

但我的问题是,std :: remove_if的内部工作原理是什么,它强加了容器的元素不是const

Che*_*Alf 5

通常std::remove_if会将项目值混洗以将逻辑上擦除的值放在序列的末尾(它通常与成员函数结合使用erase以实际删除逻辑上擦除的值).当物品不可复制或移动时,它不能进行洗牌.而是使用std::list::remove_if.


Ami*_*ory 4

如果您查看 的类型和迭代器要求std::remove_if,您可以看到实现必须类似于以下内容(来自上面的链接):

template<class ForwardIt, class UnaryPredicate>
ForwardIt remove_if(ForwardIt first, ForwardIt last, UnaryPredicate p)
{
    first = std::find_if(first, last, p);
    if (first != last)
        for(ForwardIt i = first; ++i != last; )
            if (!p(*i))
                *first++ = std::move(*i);
    return first;
}
Run Code Online (Sandbox Code Playgroud)

即,该算法仅假设迭代器具有前向能力,并且元素是可移动的,并且move元素是四处移动的。当然,move不能对const对象执行 s 操作。