Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 477
Daniel Langr Avatar asked Nov 13 '17 09:11

Daniel Langr


2 Answers

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; });
like image 84
user2807083 Avatar answered Sep 28 '22 05:09

user2807083


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.

like image 43
pptaszni Avatar answered Sep 28 '22 04:09

pptaszni