我试图将我的问题缩小到一个最小的例子:
#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_type
是std::pair<const Key, T>
, 不是 std::pair<Key, T>
.没有&符号的版本复制每一对。因为你可以复制 const Key
至 Key
一切都好。添加 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/