通过非自动非常量左值引用时 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 的错误,其中一些说:

cannot bind non-const lvalue reference of type 'std::pair&' to an rvalue of type '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 语句中?

根据这个答案: 第一个 for_each 应该可以工作(而且我还找到了另一个说同样的话的答案)。

在线验证码: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 documentation 中的 value_type 成员类型。

在您的下一行中,auto 有效,因为它自动将 Key 声明为 const