operator[] in std::map

Discussion in 'C++' started by Fab, Nov 11, 2012.

  1. Fab

    Fab Guest

    Dear all

    I use std::map for some application. I would like to return a const
    reference to some value with the operator[] function. I have a public
    method of the following form:

    const value& getValue( const int i ) const
    {
    return myMap;
    }

    where myMap is of type std::map. When I compile this with gcc, I get an
    error due to the const method qualifier. I can't figure out why? When
    I do the return statement like:

    return myMap.find( i )->second;

    then everything works. I find the first method more elegant, but like I
    said, why is this not working?

    Thanks + regards
    Fab
     
    Fab, Nov 11, 2012
    #1
    1. Advertising

  2. Fab

    Ian Collins Guest

    On 11/12/12 10:20, Fab wrote:
    > Dear all
    >
    > I use std::map for some application. I would like to return a const
    > reference to some value with the operator[] function. I have a public
    > method of the following form:
    >
    > const value& getValue( const int i ) const
    > {
    > return myMap;
    > }
    >
    > where myMap is of type std::map. When I compile this with gcc, I get an
    > error due to the const method qualifier. I can't figure out why?


    Map's operator[] isn't const. It will modify the map (by inserting a
    default value) if the element does not exist.

    --
    Ian Collins
     
    Ian Collins, Nov 11, 2012
    #2
    1. Advertising

  3. Fab

    Zhihao Yuan Guest

    > > Map's operator[] isn't const. It will modify the map (by inserting a
    >
    > > default value) if the element does not exist.

    >
    >
    >
    >
    >
    > indeed. there is one more drawback - operator[] requires that "value" is
    >
    > default constructable (because of reasons described above).
    >


    And for the same reason, you should use insert() to add new values; no temporary is needed.
     
    Zhihao Yuan, Nov 13, 2012
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Peter Jansson
    Replies:
    5
    Views:
    6,350
    Ivan Vecerina
    Mar 17, 2005
  2. Geoffrey S. Knauth
    Replies:
    6
    Views:
    1,010
    Earl Purple
    Jan 18, 2006
  3. Replies:
    1
    Views:
    434
    red floyd
    Dec 21, 2008
  4. Thomas J. Gritzan
    Replies:
    6
    Views:
    1,033
    James Kanze
    Dec 22, 2008
  5. James Kanze
    Replies:
    0
    Views:
    2,025
    James Kanze
    Dec 21, 2008
Loading...

Share This Page