views:

81

answers:

1

Hi guys,

I have a question regarding the passing of a map by reference. Let's consider the following piece of codes:

void doNotChangeParams(const map<int, int>& aMap){

    if (aMap.find(0) != aMap.end()){
        cout << "map[0] = " << aMap[0] << endl;
    }
}

and I'm having a map myMap and make a call like this: doNotChangeParams(myMap)

Now, it can be seen that I'm not modifying the parameter aMap inside the function. Nevertheless my g++ compiler complains that the access aMap[0] discards the qualifier const.

I'm putting const since I want to both tell readers of this function that I'm not modifying the argument. Also, it helps throws compile errors when I accidentally modify the map.

Currently, I have to drop the const and I think it would make the above meaning unclear to the reader from the signature of the method. I know a comment would do, but I figure I would just ask in case you know of any "programmatic" ways.

Thanks, guys.

+4  A: 

The [] operator on std::map is non-const. This is because it will add the key with a default value if the key is not found. So you cannot use it on a const map reference. Use the iterator returned by find instead:

typedef map<int, int> MyMapType;

void doNotChangeParams(const MyMapType& aMap){
    MyMapType::const_iterator result = aMap.find(0);
    if (result != aMap.end()){
        cout << "map[0] = " << result->second << endl;
    }
}
Fred Larson
Which begs the question, why didn't the standard allow a const version of operator [] that doesn't add a key?
Mark Ransom
@Mark Ransom: I think that question was discussed here on SO somewhere. Now I suppose I'll have to go find it.
Fred Larson
Maybe this: http://stackoverflow.com/questions/1639544/why-does-stdmap-operator-create-an-object-if-the-key-doesnt-exist/1639573#1639573
Fred Larson
Thanks Fred and Mark! I personally believe, purely from the standpoint of clarity, that the feature of implicit adding the key through [] is dangerous. While it's certainly good to do map[x] = y; when I write y = map[x], I'm hardly trying to add x to map in 99% of my usuage. In 99% of the case, I'm doing that to get the value of x in map if it's already there. If not, let me know by setting y to some special value. But it's good to know this "feature" of C++. Again, thanks for helping. And thanks for the link!
hungh3
@hungh3: If you really want to thank me, accept my answer (click that check mark under the vote count). 8v)
Fred Larson