STL card stores key search

I just found out that when I search for a map, for example:

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

The keys I'm looking for begin to form part of the map. In the above value, values ​​are stored as zeros. In the case of pointers, it stores values ​​as 0 significant pointers

I search with the [] operator, for example:

  int a = aMap["some key"];

Can you confirm this? I think I misinterpreted the operator []. Does this task complete ?!

Where can I find the STL documentation about these "features"?

+3
source share
7 answers

Are you looking for it with the [] operator? If yes, then yes, this is a specific behavior.

You should use the Find method if you do not want this behavior.

STL .

+8

[], , . "", , . , [] , , , .

+3

: []

T& operator[](KEY k)

NULL, . STL , .

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

, " " :

  • , , " ".
  • "- " , "Some Key" ​​ . .

, ( ):

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

???

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

, [], .

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

, , ..

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

. map:: find.

, , .

+1

[], :

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

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

As for where to find information about this behavior, the best book in the standard library is the C ++ Standard Library from Nicolai Josuttis .

+1
source

Source: https://habr.com/ru/post/1708282/


All Articles