所以,我遇到了std :: map,lambda和stl算法(remove_if)的問題。實際上,與std :: list或std :: vector相同的代碼運行良好。map,lambda,remove_if
我測試的例子:
#include <map>
#include <iostream>
#include <algorithm>
struct Foo
{
Foo() : _id(0) {}
Foo(int id) : _id(id)
{
}
int _id;
};
typedef std::map<int, Foo> FooMap;
int main()
{
FooMap m;
for (int i = 0; i < 10; ++i)
m[i + 100] = Foo(i);
int removeId = 6;
// <<< Error here >>>
std::remove_if(m.begin(), m.end(), [=](const FooMap::value_type & item) { return item.second._id == removeId ;});
for (auto & item : m)
std::cout << item.first << " = " << item.second._id << "\n";
return 0;
}
錯誤消息:
In file included from /usr/include/c++/4.6/utility:71:0,
from /usr/include/c++/4.6/algorithm:61,
from main.cxx:1:
/usr/include/c++/4.6/bits/stl_pair.h: In member function ‘std::pair<_T1, _T2>& std::pair<_T1, _T2>::operator=(std::pair<_T1, _T2>&&) [with _T1 = const int, _T2 = Foo, std::pair<_T1, _T2> = std::pair<const int, Foo>]’:
/usr/include/c++/4.6/bits/stl_algo.h:1149:13: instantiated from ‘_FIter std::remove_if(_FIter, _FIter, _Predicate) [with _FIter = std::_Rb_tree_iterator<std::pair<const int, Foo> >, _Predicate = main()::<lambda(const value_type&)>]’
main.cxx:33:114: instantiated from here
/usr/include/c++/4.6/bits/stl_pair.h:156:2: error: assignment of read-only member ‘std::pair<const int, Foo>::first’
我不明白什麼是錯在這裏。所以,我很樂意閱讀一些關於它的建議/方向。我的目標 - 使用新的lambda樣式與std :: map和算法,如remove_if。
g ++ 4.6,-std = C++ 0x。
'remove_if'接受一對迭代器,並返回一個迭代器。你認爲它從**中刪除了元素**? – 2012-03-01 11:35:17