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.
Best Answer
map::operator[]
is a little odd. It does this:Step 3 is incompatible with
const
ness. Rather than have two differently-functioningoperator[]
overloads, the language forces you to usemap::find
forconst
objects.Alternately, one could argue, what would
map::operator[] const
do if the argument is not in the map? Throw an exception? Undefined behavior? (After all, that's whatvector::operator[]
does with an index out of bounds.) In any case, the problem is avoided with only a small inconvenience to us.my_map.find(key)
returnsmy_map.end()
if thekey
is not found.