Just used unordered_map, let's learn.
As the name suggests, this is the unsorted map structure.
The template is defined as follows:
template < class Key, // unordered_map::key_type
class T, // unordered_map::mapped_type
class Hash = hash<Key>, // unordered_map::hasher
class Pred = equal_to<Key>, // unordered_map::key_equal
class Alloc = allocator< pair<const Key,T> > // unordered_map::allocator_type
> class unordered_map;
Including key-value pairs, hash rules, comparison rules, and specify the type of allocator object.
Internally, the elements in unorder_map are not sorted according to any specific order of their keys or mapped values, but are organized into buckets according to their hash values to allow direct and quick access to individual elements through their key values (average time complexity) Constant).
There are four ways to construct an unordered_map:
1, empty construction
2, copy construction
3, move construction
4, range construction
5, initial value construction
Let’s take a look at an official sample code to understand:
// constructing unordered_maps
#include <iostream>
#include <string>
#include <unordered_map>
typedef std::unordered_map<std::string,std::string> stringmap;
stringmap merge (stringmap a,stringmap b) {
stringmap temp(a); temp.insert(b.begin(),b.end()); return temp;
}
int main ()
{
stringmap first; // empty
stringmap second ( {
{
"apple","red"},{
"lemon","yellow"}} ); // init list
stringmap third ( {
{
"orange","orange"},{
"strawberry","red"}} ); // init list
stringmap fourth (second); // copy
stringmap fifth (merge(third,fourth)); // move
stringmap sixth (fifth.begin(),fifth.end()); // range
std::cout << "sixth contains:";
for (auto& x: sixth) std::cout << " " << x.first << ":" << x.second;
std::cout << std::endl;
return 0;
}
function | Features |
---|---|
begin | Returns the forward iterator of the first key-value pair |
end | Returns the forward iterator of the position after the last key-value pair |
cbegin | Same as begin, but with the addition of the const attribute, the returned iterator cannot be used to modify the content |
a few | Same as end, but with the addition of the const attribute, the returned iterator cannot be used to modify the content |
empty | Return true if empty, otherwise return false |
size | Returns the number of key-value pairs |
max_size | Returns the maximum number of key-value pairs that can be accommodated, the results of different systems are different |
operator[key] | It can be operated by subscript like an array. If the current subscript does not have a key-pair value, insert a new key-pair value |
at(key) | Return the value corresponding to the key, if it does not exist, return the out_of_range exception |
The pit that the predecessors stepped on with unordered_map: the pit of unordered_map
For more information, you can go to the official website to see: STL: unordered_map
or see: Programming Network