[英]const arguments in std::remove_if
我要從對列表中刪除元素。 當我使用一對像
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;
}
}
我知道(如果我錯了,請糾正我):
只要列表的任何元素中存在list <const int>
,我就會遇到完全相同的問題,例如, list <const int>
也會返回編譯錯誤。
如果我刪除對中第一個元素中的const,代碼將起作用。
更優雅和有效的方法是使用remove_if list方法,如下所示:
l.remove_if([id](std::pair<const int, bool>& e) -> bool { return e.first == id; });
但我的問題是,std :: remove_if的內部工作原理是什么,它強加了容器的元素不是const ?
一般std::remove_if
將項值改為std::remove_if
,將邏輯擦除的值放在序列的末尾(它通常與成員函數erase
結合使用,以實際刪除邏輯上擦除的值)。 當物品不可復制或移動時,它不能進行洗牌。 而是使用std::list::remove_if
。
如果查看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;
}
即,該算法僅假設迭代器具有前向能力,並且元素是可移動的,並且它move
s元素。 當然,不能在const
對象上執行move
s。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.