C++ map key does not exist

C++ map considerations

1. In the map, when looking up the value by the key, it is first necessary to determine whether the map contains the key.

2. If you do not check and return map[key] directly, unexpected behavior may occur. If the map contains the key, there is no problem. If the map does not contain the key, the use of subscripts has a dangerous side effect. An element of the key will be inserted into the map. The value takes the default value and returns the value. That is, it is impossible for map[key] to return null.

3. The map provides two ways to check whether the key is included, m.count(key), m.find(key).

4. m.count(key): Since the map does not contain duplicate keys, the value of m.count(key) is 0, or 1, indicating whether it is included.

5. m.find(key): Returns an iterator to determine whether it exists.

6. For the following scenarios, use the key if it exists, otherwise return null. There are two ways to write:

1 if(m.count(key)>0)
2 {
3     return m[key];
4 }
5 return null;
1 iter = m.find(key);
2 if(iter!=m.end())
3 {
4     return iter->second;
5 }
6 return null;

Note here: the former method is intuitive, but much less efficient. Because of the previous method, two lookups need to be performed. Therefore, the latter method is recommended.

7. For containers in STL, there is a generic algorithm find(begin, end, target) to find the target, and map also provides a member method find(key)


Original link: http://www.cnblogs.com/nzbbody/p/3409298.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325936161&siteId=291194637