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

Dan*_*ica 3 c++ foreach lambda reference auto

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

不能将'std :: pair&'类型的非const左值引用绑定到'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;
}
Run Code Online (Sandbox Code Playgroud)

是什么导致这个错误?它是如何工作的auto,即在第二个for_each声明中?

根据这个答案:https://stackoverflow.com/a/14037863/580083第一个for_each应该工作(我也发现另一个答案,说同样的).

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

use*_*083 6

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

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

  • 另见[`value_type`](http://de.cppreference.com/w/cpp/container/map) (4认同)