Some points to note in the use of associative containers
- There are mainly map and set, and unordered and multi versions are derived.
map
- Each element in the map is a
[key,value]
pair object, and the key and value can be accessed through first and second. During the operation, the value can be modified, but the key cannot be modified.
multiset/multimap
- For map and set, there are no repeated elements, so you can directly determine whether the container contains a specific element through find
- For multimap and multiset, the same elements will be stored in adjacent positions, so if you find the first position, you can find the values stored later in turn
code
void test() { multimap<int, string> maps; maps.insert( make_pair(1, "a") ); maps.insert(make_pair(1, "b")); maps.insert(make_pair(2, "d")); maps.insert(make_pair(1, "c")); maps.insert(make_pair(3, "e")); int cnt = maps.count( 1 ); auto it = maps.find( 1 ); while (cnt-- != 0) cout << it++->second << endl; }
lower_bound,upper_bound
lower_bound
is an iterator that returns the first greater than or equal to the container position where the specified element is locatedupper_bound
is an iterator that returns the first greater than the container position where a particular element is located- The above 2 functions can also be used to find out those values in a (sorted) container that are equal to a specific element
- For the container of the set category, you can use the generic algorithm or the function implemented by yourself to implement lower_bound/upper_bound, but for the container of the map category, it is recommended to use the function implemented by the map class; if you want to use the generic algorithm of stl to implement lower_bound/upper_bound, then Need to give pair
unordered container
- Those classes at the beginning of unordered, implemented with a hash table, can be
O(1)
searched.