如何通过引用为C++ 0x传递Lambda表达式参数

Gop*_*lem 6 c++ lambda std c++11

我正在使用C++ 0x lambda表达式来修改地图的值.

但是,通过引用传递map迭代器有困难.

如果我只是通过迭代器,通过如下值:[](std::pair<TCHAR, int > iter)它编译得很好,但值不会在地图中更新.

如果我尝试通过引用传递迭代器,例如[](std::pair<TCHAR, int >& iter)VS2010编译器抱怨它

cannot convert paramater from 'std::pair<_Ty1,_Ty2>' to 'std::pair<_Ty1,_Ty2> &'
Run Code Online (Sandbox Code Playgroud)

这是代码.欣赏有关如何使用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;
}
Run Code Online (Sandbox Code Playgroud)

谢谢

ngo*_*eff 4

问题是你不允许修改地图的键。

std::for_each(charToInt.begin(), charToInt.end(), [](std::pair<const TCHAR, int>& iter)
Run Code Online (Sandbox Code Playgroud)

会起作用,因为它使用const TCHAR.

编辑:

正如@David和其他发帖者所指出的,在这种情况下,您最好使用Map::value_type&它的 typedef std::pair<const TCHAR, int>&,因为如果您稍后更改您正在使用的地图中的类型,您也不需要更改循环代码。

作为参考,这里是完整的错误消息,您可以在其中看到它正在尝试在两种不同类型的对之间进行转换,一个为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
    ]
Run Code Online (Sandbox Code Playgroud)

  • +1 用于诊断 hte 问题,但更好的解决方案是使用“Map::value_type&amp;”,因为意图更清晰且不易出错。 (3认同)