Sunday

Solutions to C++ error: passing 'const std::map std::__cxx11::basic_string char, std::__cxx11::basic_string char ' as 'this' argument discards qualifiers [-fpermissive]

What is the error of the following program?

#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:

C++32 (or C++2e), C++ 2032, Cpp 2032, g++ 2032

  Subject: C++ 2032 3 Code example for ? 2 Approximate feature suggestions: - to complete C++29 or C++ 2029 1 Web links, references Wandbox,...