Quick Q: Why does std::map not have a const accessor? -- StackOverflow

To help balance out "introductory," "intermediate," and "advanced" content, we're trying an experiment to highlight interesting bite-sized tidbits that are in the first two categories.

Here's today's tidbit from StackOverflow's [c++11] tag:

The declaration for the [] operator on a std::map is this:

T& operator[] ( const key_type& x );

Is there a reason it isn't this?

T& operator[] ( const key_type& x );

const T& operator[] const ( const key_type& x );

Because that would be incredibly useful any time you need to access a member map in a const method.

As the two top answers show, the answer is different in C++98 and C++11, and C++11 is where it's "at" (pardon).

Read answers on StackOverflow...

Add a Comment

Comments are closed.

Comments (3)

1 0

ben.craig said on Dec 16, 2012 02:26 PM:

I'm glad to see this article. There has been a lot of information about some of the new, flashy features in C++11. There hasn't been as much attention given to some of the "minor" standard library changes. Sure, copy_if got a little bit of press, but there hasn't been much discussed about vector::emplace, and this is the first I've seen about map::at.
0 0

Grunt said on Dec 16, 2012 02:31 PM:

I like this, for a start. Good to know the admins read the comments! My only concern is a potential - shall we say - comment slicing issue. To comment here or on S.O.? Also, I still think it would behoove the community to tag items by their presumed target audience, so that readers know what to expect. BTW, I appreciate all who have taken the time to educate - especially Stroustrup - and make this site better.
0 0

Joel Lamotte said on Dec 16, 2012 05:21 PM:

This list of C++11 questions could be useful too (just sorted by vote): http://stackoverflow.com/questions/tagged/c++11?sort=votes&pagesize=50