Search code examples
c++dictionarystdstdmapconst-correctness

Why can't I use operator[] with a const std::map?


I tried to pass const with vector it works: Ex:

void damn(const vector <bool> &bb)
{
    for (int i = 0; i < bb.size(); i++)
        cout << bb[i] << endl;
}

But when trying with map, it does not:

void pas(const map <string, float> &mm)
{
    cout << mm["a"];
    cout << mm["b"];
}

I wonder why it doesn't.


Solution

  • I believe that it is because [] in map isn't const, as it creates new pair with default value, if you address to nonexisting one. Try

    void pas(const map <string, float> &mm)
    {
        cout<<mm.find("a")->second;
        cout<<mm.find("b")->second;
    }