のリストのリストから要素を削除します。私はstd :: remove_if内のconst引数
std::pair<const int, bool>
のようなペアを使用しているとき、私は次のコンパイルエラーが表示されます。
In file included from /usr/local/include/c++/6.1.0/utility:70:0,
from /usr/local/include/c++/6.1.0/algorithm:60,
from main.cpp:1:
/usr/local/include/c++/6.1.0/bits/stl_pair.h: In instantiation of '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: required from '_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: required from '_FIter std::remove_if(_FIter, _FIter, _Predicate) [with _FIter = std::_List_iterator > _Predicate = main()::&)>]'
main.cpp:17:32: required from here
/usr/local/include/c++/6.1.0/bits/stl_pair.h:319:8: error: assignment of read-only member '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;
}
}
私は(修正してくださいことを知っています私が間違っている場合):
リストのどの要素にもconstanceがある限り、まったく同じ問題が発生します。例えば、
list <const int>
もコンパイルエラーを返します。ペアの最初の要素のconstを削除すると、コードが機能します。それを行うには
よりエレガントかつ効率的な方法は、このように、remove_ifリスト方式を使用することです:
l.remove_if([id](std::pair<const int, bool>& e) -> bool { return e.first == id; });
が、私の質問は正確にSTDの内部の仕組みどのようなものであり、::コンテナの要素がconstではないremove_if?
'std :: remove_if'は逆参照型を* MoveAssignable *にする必要があります。これは' std :: pair 'はそうではありません。 –
user657267