c++ - Lambda 和映射,通过引用传递参数 - 编译错误

标签 c++ c++11 lambda

我试图将我的问题缩小到一个最小的例子:

#include <algorithm>
#include <map>
#include <string>
#include <vector>

int main()
{
    std::vector<int> result;
    std::map<std::string, std::pair<unsigned int, std::vector<int>>> other;

    if (true)
    {
        std::for_each(other.begin(), other.end(),
            [&](std::pair<std::string, std::pair<unsigned int, std::vector<int>>> & data)
            {
                result.insert(result.end(), data.second.second.begin(), data.second.second.end());
            });
    }

    return 0;
}

我得到一个编译器错误:

error C2664: 'void main::<lambda_1b93236899a42921c1aec8d5288e5b90>::operator ()(std::pair<std::string,std::pair<unsigned int,std::vector<int,std::allocator<_Ty>>>> &) const': cannot convert argument 1 from 'std::pair<const _Kty,_Ty>' to 'std::pair<std::string,std::pair<unsigned int,std::vector<int,std::allocator<_Ty>>>> &'

据我所知,lambda 参数确实是对我们正在迭代的映射所包含的类型的引用。那是我应该使用的类型,对吧?

如果我在 data 之前删除 amperstand,它会编译。

为什么?

我不想按值传递每个元素,因为这些集合在我的实际程序中将包含大量数据。

如果我用 auto & 替换 lambda 参数,它会编译,这让我相信 lambda 参数中的类型与映射中包含的类型不匹配,但看起来确实如此大部头书。另外,如果类型错误,为什么没有 & 的原始编译?

我缺少/不理解什么?

最佳答案

std::map<Key, T> value_typestd::pair<const Key, T> , 不是 std::pair<Key, T> .没有&符号的版本复制每一对。因为你可以复制 const KeyKey一切都好。添加 const到您的 lambda 的参数类型。

#include <algorithm>
#include <map>
#include <string>
#include <vector>

int main()
{
    std::vector<int> result;
    std::map<std::string, std::pair<unsigned int, std::vector<int>>> other;

    if (true)
    {
        std::for_each(other.begin(), other.end(),
            [&](std::pair<const std::string, std::pair<unsigned int, std::vector<int>>> & data)
        // Add this const ^^^^^
        {
            result.insert(result.end(), data.second.second.begin(), data.second.second.end());
        });
    }

    return 0;
}

关于c++ - Lambda 和映射,通过引用传递参数 - 编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43987171/

相关文章:

c++ - 重载 [] 和 , c++11

c++ - 我在 C++ 中遇到了一个奇怪的错误,其中计算 2 个小整数相加的语句溢出到一个 long long 值

c# - Entity Framework ,枚举支持 : Modify Expression in Linq Extension Method

c++ - QT 小部件插槽调用未被单独的线程信号激活

c++ - Visual Studio 预处理器仅在设置了/P 时才有效

c++ - 错误 : name lookup of ‘x’ changed for ISO ‘for’ scoping

python - Python3 中减少错误的 lambda

node.js - 读取 aws lambda 包中的打包文件

c++ - QToolbar的句柄是什么类型的组件?

c++读取文件并将整数存储在 vector 中。最终占用的内存比实际文件大小多 5 倍