0

Get the error error: passing 'const std::map<int, int>' as 'this' argument discards qualifiers [-fpermissive] when codes below work.

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <map>

using namespace std;


int main() {
    std::map<int, int> test_map;
    std::vector<int> test_vec({0,1,2,3});
    test_map[0] = 1;
    test_map[1] = 2;
    for_each(test_vec.begin(), test_vec.end(), [test_map](auto i) {
        if (test_map.find(i) != test_map.end()) {
            test_map[i] += 10;
        }
    });
    return 0;
}

In lambda capture list, test_map is a non-const container, but it become const in the lambda body. why?

  • 4
    Why are you passing `test_map` by value, if you want to modify this map ? Should be `&test_map`, which resolves your problem. Now, you capture `test_map` by value, so you can only read this map inside lambda because by default `operator()` of closure is const qualified (`operator[]` of map is non-const function member). If you want really to modify copy of map, mark lambda as `mutable`. – rafix07 Apr 13 '21 at 06:41
  • @Ted Lyngmo yeah, the key of map is **const**, but it does not change the key, it changes the value. – liangzelang Apr 13 '21 at 06:41
  • @liangzelang So it does ... :-) My bad. `[&test_map]` should fix that as rafix07 mentions. – Ted Lyngmo Apr 13 '21 at 06:45
  • rafix07 is right and this is probably a duplicate. See: [Why is a lambda's call-operator implicitly const?](https://stackoverflow.com/questions/53445857/why-is-a-lambdas-call-operator-implicitly-const) – Blastfurnace Apr 13 '21 at 06:47
  • @Blastfurnace Great question that you have pointed to. Thank you. – Aditya Singh Rathore Apr 13 '21 at 07:32

0 Answers0