我正在使用C++ 0x lambda表达式修改映射的值。如何通过C++的参考传递Lambda表达式参数0x
但是,难以通过引用传递映射迭代器。
如果我只是通过迭代器,值如:[](std::pair<TCHAR, int > iter)
编译好,但值不会在地图上更新。
如果我试图通过引用传递迭代器,如[](std::pair<TCHAR, int >& iter)
VS2010的编译器抱怨说,它
cannot convert paramater from 'std::pair<_Ty1,_Ty2>' to 'std::pair<_Ty1,_Ty2> &'
这里是代码。欣赏关于如何使用lambda表达式修改std :: map对象的信息。
#include <tchar.h>
#include <map>
#include <algorithm>
#include <vector>
int _tmain(int argc, _TCHAR* argv[])
{
typedef std::map<TCHAR, int > Map;
Map charToInt;
charToInt[_T('a')] = 'a';
charToInt[_T('b')] = 'b';
charToInt[_T('c')] = 'c';
charToInt[_T('d')] = 'd';
std::for_each(charToInt.begin(), charToInt.end(), [](std::pair<TCHAR, int >& iter)
{
int& val = iter.second;
val++;
});
return 0;
}
谢谢
+1用于诊断hte问题,但更好的解决方案是使用'Map :: value_type&',因为意图更清晰且不易出错。 – 2010-10-05 11:15:58
谢谢 - 这些建议正在起作用。 – 2010-10-06 00:51:18