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