传递非自动常量左值引用时,for_each、map和lambda出错

Error with for_each, map and lambda when passing by non-auto non-const lvalue reference

本文关键字:each for map 出错 lambda 常量 引用      更新时间:2023-10-16

在下面的代码中,第一个for_each语句给了我GCC 7.2的错误,其中一些错误说:

无法绑定类型为"std::pair&"的非常量左值引用到类型为"std::pair"的右值

#include <algorithm>
#include <iostream>
#include <map>
int main() {
std::map<int, double> m = { {1, 1.0}, {2, 2.0}, {3, 3.0} };
std::for_each(std::begin(m), std::end(m),
[](std::pair<int, double>& e){ e.second += 1.0; }); // ERROR
std::for_each(std::begin(m), std::end(m),
[](auto& e){ e.second += 1.0; }); // OK
for (auto iter = std::begin(m); iter != std::end(m); ++iter)
iter->second += 1.0;
for (auto & e : m)
e.second += 1.0;
for (auto & [ key, value ] : m)
value += 1.0;
std::cout << m[1] << ", " << m[2] << ", " << m[3] << std::endl;
}

导致此错误的原因是什么?它是如何与auto一起工作的,即在第二个for_each语句中?

根据这些答案:https://stackoverflow.com/a/14037863/580083第一个CCD_ 4应该起作用(我也找到了另一个答案,也同样如此)。

在线代码:https://wandbox.org/permlink/mOUS1NMjKooetnN1

您不能修改std::map的密钥,所以您应该使用

std::for_each(std::begin(m), std::end(m),
[](std::pair<const int, double>& e){ e.second += 1.0; });

试试这个:

std::for_each(std::begin(m), std::end(m),
[](std::pair<const int, double>& e){ e.second += 1.0; });

将对中的Key元素声明为const是至关重要的。请参阅std::map文档中的value_type成员类型。

在您的下一行中,auto起作用,因为它自动将Key声明为const