Blog Archive

Sunday, July 28, 2019

How to solve the error with passing const std::unordered_map or passing const std::map

// Example program
#include <iostream> #include <string> #include<unordered_map> using namespace std; void printMap(const unordered_map<int, int> m){ for(auto item:m){ cout<< item.first << " " << item.second<<" "; cout<< item.first << " " << m[item.first]<<endl; //cout<< item.first << " " << m.at(item.first)<<endl; } return; } int main() { unordered_map<int, int> m; m[0]=10; m[1]=20; printMap(m); return 0; }


Question: How to solve the following error:
9:49: error: passing 'const std::unordered_map<int, int>' as 'this' argument of
'std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::mapped_type&
std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::operator[](const key_type&)
[with _Key = int; _Tp = int; _Hash = std::hash<int>; _Pred = std::equal_to<int>;
_Alloc = std::allocator<std::pair<const int, int> >;
std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::mapped_type = int;
std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::key_type = int]'
discards qualifiers [-fpermissive]


Answer:
using at() to access the element of map or unordered_map
Solution:
cpp.sh/7rmyz


No comments:

Post a Comment