0

I am struggling with understanding why auto p in the following code snippet is const type, which prevents the query cnt_w[p.first]. I understand the error msg error: no viable overloaded operator[] for type 'const std::unordered_map<char,intmstd::hash<char>, because in c++,when the key is not existed in the unordered_map, it will implement insertion. Could you please enlighten me why auto p is const_iterator? or when did my cnt_t, cnt_w become const type? It really confuses me pretty hard.

#include <bits/stdc++.h>

using namespace std;

#include <iostream>

int main(void) {
    unordered_map<char, int> cnt_t, cnt_w;
    string t = "ABCF";
    string s = "ABCF";
    for (auto c: t)
        cnt_t[c] += 1;
    for (auto c: s)
        cnt_w[c] += 1;
    if (all_of(cnt_t.begin(), cnt_t.end(), [cnt_w = &cnt_w](auto p) { return cnt_w[p.first] >= p.second; }))
        cout << "TRUE" << endl;
    return 0;
}

I know I can use cnt_w.at(p.first) instead of cnt_w[p.first] to avoid the error: passing ‘const std::unordered_map<char, int>’ as ‘this’ argument discards qualifiers as shown below, but cnt_w.at(p.first) would cause an error when the key is not existed.

int main(void) {
    unordered_map<char, int> cnt_t, cnt_w;
    string t = "ABCF";
    string s = "ABCF";
    for (auto c: t)
        cnt_t[c] += 1;
    for (auto c: s)
        cnt_w[c] += 1;
    if (all_of(cnt_t.begin(), cnt_t.end(), [cnt_w = cnt_w](auto p) { return cnt_w.at(p.first) >= p.second; }))
        cout << "TRUE" << endl;
    return 0;
}
Albert G Lieu
  • 891
  • 8
  • 16

1 Answers1

3

You're doing wrong in the first case. You should use [&cnt_w = cnt_w] or just [&cnt_w]. cnt_w here is non-const.

What you're doing is getting the address of cnt_w

Nimrod
  • 2,908
  • 9
  • 20
  • thank @Nimrod very much. Yes, ````[&cnt_w = cnt_w]```` and ````[&cnt_w]```` work well. Could you please explain the meaning of ````[&cnt_w = cnt_w]```` and ````[&cnt_w] ````? Ang why ````[cnt_w = cnt_w]```` failed? I am teaching my c++ with a background in python. Thank you very much. – Albert G Lieu Dec 24 '21 at 07:53
  • 2
    Sure. `&` here means `cnt_w` is captured by (non-const) reference, while `[cnt_w = cnt_w]` or `[cnt_w]` means `cnt_w` is captured by copy, which is const. see more [here](https://en.cppreference.com/w/cpp/language/lambda) – Nimrod Dec 24 '21 at 08:06