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

标签 c++ lambda c++11 std

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

相关文章:

c++ - 如何在 C++ 中定义可变大小的 vector

c++ - 在 Qt5 的 QWidget 中添加新按钮

python - lambda 表达式在 Python 中接受两个参数时出错

c# - 如何使用 lambda 表达式创建扩展方法

c++ - 被删除的构造函数 "accessible"吗?

c++ - 为什么 std::map 上基于范围的 for 循环中的 const std::pair<K,V>& 不起作用?

c++ - 如何在开发机器上重现缺少 Qt 插件的问题?

c++ - Qt调整窗口大小以适应滚动区域问题中的纵横比

c# - Lambda 表达式转换

c++ - 如何在kali linux的make命令中启用c++11