For Programmers: Free Programming Magazines  


Home > Archive > VC STL > August 2005 > std::map operator [ ]









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author std::map operator [ ]
everguet@gmail.com

2005-08-04, 9:07 am

Hi,

What is the returned value of m_list["Foo"] if "Foo" string was never
added to map ? Do i need to perform a find before accessing my map ?

Thanks.

Stephen Howe

2005-08-04, 9:07 am

> What is the returned value of m_list["Foo"] if "Foo" string was never
> added to map ? Do i need to perform a find before accessing my map ?


It is the default of the value element.
So with

map<string, int>

"Foo" key will be added if not present, by the [] operator and the value
element will be 0.
[] behaves like an update on the value element if the key is present and
like an insert if not present.

Stephen Howe




Jason Winnebeck

2005-08-04, 9:07 am

everguet@gmail.com wrote:
> Hi,
>
> What is the returned value of m_list["Foo"] if "Foo" string was never
> added to map ? Do i need to perform a find before accessing my map ?
>
> Thanks.
>

everguet@gmail.com wrote:
> Hi,
>
> What is the returned value of m_list["Foo"] if "Foo" string was never
> added to map ? Do i need to perform a find before accessing my map ?
>
> Thanks.
>


operator[] for a map will construct a new element with the default
constructor to be the value for "Foo". Then it will add that value to
the map with the key "Foo" and then return the value. Therefore,
operator[] always succeeds in returning some value that is in the map.

If you don't want to have a modification happen if the element does not
exist, then you have to use find.

Jason
everguet@gmail.com

2005-08-04, 9:07 am

Thanks all ;)

Simon Trew

2005-08-11, 10:02 pm

I think it is worth saying that if you don't use [], the class doesn't need
to have a default constructor.

S.

<everguet@gmail.com> wrote in message
news:1123158726.067503.79620@g49g2000cwa.googlegroups.com...
> Hi,
>
> What is the returned value of m_list["Foo"] if "Foo" string was never
> added to map ? Do i need to perform a find before accessing my map ?
>
> Thanks.
>



Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com