我试图将我的问题缩小到一个最小的例子:
#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;
}
Run Code Online (Sandbox Code Playgroud)
我收到编译器错误:
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>>>> &'
Run Code Online (Sandbox Code Playgroud)
据我所知,lambda参数确实是对我们正在迭代的地图所包含的类型的引用.这是我应该使用的类型,对吧?
如果我在data编译之前删除了amperstand .
为什么?
我不想按值传递每个元素,因为这些集合将在我的真实程序中包含大量数据.
如果我用auto &它编译替换lambda param,这会让我相信lambda param中的类型与map中包含的类型不匹配,但它看起来确实对我有用.另外,为什么原始编译没有&如果类型错误?
我错过了什么/不理解?
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
200 次 |
| 最近记录: |