[英]Lambda copying a reference to a lambda reference VS2017 compile error
[英]Lambda and map, param by reference - compile error
我試圖將我的問題縮小到一個最小的例子:
#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 param,這讓我相信lambda param中的類型與地圖包含的類型不匹配,但它確實看起來像對我來說。 另外,為什么原始編譯沒有&如果類型錯誤?
我錯過了什么/不理解?
std::map<Key, T>
的value_type
是std::pair<const Key, T>
,而不是std::pair<Key, T>
。 沒有&符號的版本會生成每對的副本。 既然你可以將const Key
復制到Key
一切都很好。 在lambda的參數類型中添加一個const
。
#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;
}
我今天一直在努力解決同樣的問題。
我解決了在std::pair
const
中創建鍵值類型的問題:
[&](std::pair<const std::string, std::pair<unsigned int, std::vector<int>>> & data)
// ^^^^^
在考慮了一下之后,這是非常合乎邏輯的:
您不能將std::map
的條目的key_value
更改為不同的名稱。 因此,如果它使用auto
循環和引用,則需要將其指定為const
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.