tags:

views:

294

answers:

7

I have just found out that when I search a map like :

  std::map<std::string, int> aMap;

the keys I search start to be part of the map. In the case above the values are stored as zeros. In case of pointers it stores the values as 0 valued pointers

I am doing the search with the [] operator, like in :

  int a = aMap["some key"];

Can you confirm this ? I think I have misinterpreted the [] operator. Is it doing an assignment ?!

Where can I find STL documentation of these kind of "features" ?

+8  A: 

Are you searching it with the [] operator? If so, then yes, this is the defined behaviour.

You should use the 'find' method if you don't want this behaviour.

A good reference for the STL is the Nicolai Josuttis book.

Will Dean
+1  A: 

How do you search???

if(!aMap[key]) // not found

This is not correct, once you access a map via operator[] the apropriate place is created and the reference is returned.

You need to use

if(aMao.find(key)==aMap.end()) // not found
Artyom
+1  A: 

It sounds like you're using the bracket operator, i.e.

if (aMap["string"] == something)

Don't do that. Instead, use map::find.

The bracket operator will automatically insert the key into the map if it doesn't exist, using the default for the value part.

Mark Ransom
+3  A: 

If you look in the map using the [] operator, then, yes, you will generate default objects. If you use 'find', on the other hand, it does not. This is because the [] operator MUST return a reference to an object in the map, so it has no choice but to generate one if one is not already there.

Michael Kohne
+1  A: 

If by search you mean using operator[], like this:

if ( m["foo"] == 42 ) {
  // found
}
else {
  // not
}

then yes, that will create an entry for "foo" if it does not already exist. For this reason, you should generally avoid using operator[] for maps and use the named function sfind() and insert() instead.

As for where to find out information on this behaviour, the best book on the standard library is The C++ Standard Library by Nicolai Josuttis.

anon
+2  A: 

The reasoning behind this is: [] is defined as

T& operator[](KEY k)

A Reference can never be NULL, so some value must be returned. STL solves this by inserting a default initialized element.

ebo
+2  A: 
int a = aMap["some key"];

Here map checks to see if the key "some key" is already exists the map:

  • if yes then the reference of the value corresponding to the "Some key" is returned.
  • If "some key" doesnot exists in the map then the key "Some Key" is inserted in the map with default value. reference of the newly inserted value will be returned.

The correct way of testing whether a key exits in map (without adding the key to map) is:

std::map<key,value>::iterator iter = myMap.find("Some Key");
if( iter != myMap.end())
{
 //key exists
}
else
{
 //no key
}
aJ