我正在使用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