#include <iostream>
#include <map>
using namespace std;
void mapCout(const map<string, string>& m)
{
for(auto pair : m)
{
cout << "m[\"" << pair.first << "\"] = " << m[pair.first] << endl;
//solutions
//cout << "m[\"" << pair.first << "\"] = " << pair.second << endl;
//cout << "m[\"" << pair.first << "\"] = " << m.at(pair.first) << endl;
}
}
int main(int argc, char* argv[])
{
map<string,string> m;
string key1 = "aa";
string value1 = "apple";
m[key1] = value1;
m["bb"] = "banana";
m["cc"] = "cucumber";
mapCout(m);
return 0;
}
Solutions:
take note in function 'void mapCout(const std::map<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char> >&)'
error: passing 'const std::map<std::__cxx11::basic_string<char>,
std::__cxx11::basic_string<char> >' as
'this' argument discards qualifiers [-fpermissive]
Read The F*** Manual (Fine), read by yourself a fine C++ manual
Both the map::operator[] function declarations return a reference and non-constant to its mapped value:
mapped_type& operator[] (const key_type& k);
mapped_type& operator[] (key_type&& k);
Solution:
see at the function constant parameter "const map<string,string>& m"
map operator[] is non-constant because
it inserts the key if it does not exist
and returns a reference to its mapped value
if you want the map container to be constant,
the member function at() may be used
No comments:
Post a Comment