传递非自动常量左值引用时,for_each、map和lambda出错
Error with for_each, map and lambda when passing by non-auto non-const lvalue reference
在下面的代码中,第一个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
。
相关文章:
- C++ 中用于二维数组的 for-each 循环
- 计算 fib(n) 的次数称为 FOR EACH n
- 支持自定义 const 本机C++容器类的"for each"
- C++ for-each 语句触发"vector iterators incompatible"断言失败:this->_Getcont() == 0
- 为什么我的矢量中的项目在 C++ 中的 for-each 循环期间不会改变?
- 当循环返回"for each"项的 nullptr 时?
- 正确使用C++ 'for each'选项
- "for each"能保证使用更改数组吗?
- 基于范围的循环与 for-each 循环有何不同
- C++:从"for each"循环中的映射中删除值
- 将函数应用于std::map值,其中包含for each和lambda函数
- 正在擦除for(-each)自动循环中的项目
- g++ 4.4.7 -std=gnu++0x 应该编译"for each"结构吗?
- 将循环转移到C++03 for each
- 在 for-each 循环中使用 'auto' 时是否需要添加'const'?
- C++中的"for each"循环如何知道数组的长度
- 基本c++: for-each循环
- 如何使c++中的for each循环函数与自定义类一起工作
- 如何使用for-each循环来美化析构函数
- for-each 循环生成错误,但 for(it=begin()...在遍历 std::map 包含 unique_ptr 时不会