Error with for_each, map and lambda when passing b

2019-07-07 02:53发布

In the following code, the first for_each statement gives me errors with GCC 7.2, some of which says:

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;
}

What causes this error? How's that it works with auto, i.e., in the second for_each statement?

According to this answers: https://stackoverflow.com/a/14037863/580083 the first for_each should work (and I've also found another answer that said the very same).

Online code: https://wandbox.org/permlink/mOUS1NMjKooetnN1

2条回答
做自己的国王
2楼-- · 2019-07-07 03:26

You can't modify key of a std::map, so you should use

  std::for_each(std::begin(m), std::end(m),
            [](std::pair<const int, double>& e){ e.second += 1.0; });
查看更多
3楼-- · 2019-07-07 03:29

Try this:

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

It is crucial to declare Key element of pair as const. See the value_type member type in std::map documentation.

In your next line auto works, because it automatically declares Key as const.

查看更多
登录 后发表回答