我正在使用 C++0x lambda 表达式来修改映射的值。
但是,很难通过引用传递 map 迭代器。
如果我只是通过迭代器传递值,例如:[](std::pair<TCHAR, int > iter)
它编译正常,但 map 中的值没有更新。
如果我尝试通过引用传递迭代器,例如 [](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;
}
谢谢
最佳答案
问题是不允许修改 map 的key。
std::for_each(charToInt.begin(), charToInt.end(), [](std::pair<const TCHAR, int>& iter)
会起作用,因为它使用 const TCHAR
.
编辑:
正如@David 和其他发帖人所指出的,您最好使用 Map::value_type&
这是 std::pair<const TCHAR, int>&
的类型定义在这种情况下,因为如果您稍后更改正在使用的 map 中的类型,您也不需要更改循环代码。
作为引用,这里是完整的错误消息,您可以在其中看到它正在尝试在两种不同类型的对之间进行转换,一种是 TCHAR
。 , 另一个是 const TCHAR
...
cannot convert parameter 1 from 'std::pair<_Ty1,_Ty2>' to 'std::pair<_Ty1,_Ty2> &'
with
[
_Ty1=TCHAR,
_Ty2=int
]
and
[
_Ty1=const TCHAR,
_Ty2=int
]
and
[
_Ty1=TCHAR,
_Ty2=int
]
关于c++ - 如何通过引用为 C++0x 传递 Lambda 表达式参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3861744/