[C++]: Use of unordered_map

1. Concept

  • key

               The type of key value. Each element in unordered_map is uniquely identified by its key value.

  • T

                The type of mapped value. Each element in unordered_map is used to store some data as its mapped value.

  • Hash

                A one -dollar function object type, it accepts an object of a key type as a parameter, and returns the unique value of the size_t type based on the object. This can be a class that implements a function call operator, or a pointer to a function (see Constructors). The default is hash<Key>.

  • before

                Accepts two key type parameters and returns a binary predicate of type bool. Expression pred (a, b), pred is an object of this type, a and b are key values, return true, if it is equivalent to b, it should be considered. This can be a class implementing a function call operator or a pointer to a function (see constructor as an example). This defaults to equal_to<Key>, which returns the same result as applying the equality operator (a==b).

  • Allloc

                The type of allocator object used to define the storage allocation model. By default, the allocator class template is used, which defines the simplest memory allocation model and is value-independent.

  • unordered_map is an associative container that stores <key, value> key-value pairs, which allows fast indexing by keys to < /span>its corresponding value.
  • In unordered_map,the key value is usually used to uniquely identify the element (the key value is unique), and the map value is an object , whose contents are associated with this key. Keys and mapped values ​​may be of different types.
  • Internally, unordered_map does not sort <kye, value> in any specific order. In order to find the value corresponding to key within the constant range, unordered_map will be the same. The key-value pairs of the hash value are placed in the same bucket.
  • The unordered_map container is faster than map for accessing individual elements by key, but it is generally less efficient at traversing range iterations of a subset of elements .
  • unordered_maps implements the direct access operator (operator[]), which allows direct access to value using key as a parameter.

2. Constructor

(1) Create an empty unordered_map

    unordered_map<int, int> m;

(2) Initialization using initialization list

    unordered_map<int, int> m1({ { 1,1 } });
    unordered_map<int, int> m2({
         { 1,1 }
        ,{ 2,2 }
        ,{ 3,3 }});

(3) Copy constructor initialization

    unordered_map<int, int> m3(m2);

(4) Iterator initialization 

    unordered_map<int, int> m4(m2.begin(),m2.end());

3. Built-in functions

3.1. Capacity

(1) Test empty (return bool value)

    unordered_map<int, int> m;
    cout << m.empty();

(2) Find the size

    unordered_map<int, int> m;
    m.size();

 (3) Returns the maximum number of elements that the unordered mapping container can hold.

    unordered_map<int, int> m;
    cout << m.max_size();

3.2. Iterator

    unordered_map<int, int> v;
    v.begin();          //获取第一个数的位置
    v.end();            //获取最后一个数的位置

    unordered_map<int, string> m;
    m.emplace(make_pair(1, "yi"));
    m.emplace(make_pair(2, "er"));

    unordered_map<int, string>::iterator it = m.begin();
    while (it != m.end())
    {
        cout << (*it).first << " " << (*it).second << endl;
        it++;
    }

3.3. Element access

    unordered_map<string, string> mymap;

    mymap["Bakery"] = "Barbara";  
    mymap["Seafood"] = "Lisa";    
    mymap["Produce"] = "John";    

    string name = mymap["Bakery"];   
    mymap["Seafood"] = name;

    mymap["Bakery"] = mymap["Produce"];

    name = mymap["Deli"];      
    mymap["Produce"] = mymap["Gifts"];    

  3.4. Modifier

(1) emplace (insert)

    unordered_map<int, string> m;
    m.emplace(make_pair(1, "yi"));
    m.emplace(make_pair(2, "er"));

 (2) insert (insert)

Use is similar to emplace, but more flexible

#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;


int main()
{
    unordered_map<string, double>
        myrecipe,
        mypantry = { {"milk",2.0},{"flour",1.5} };

    pair<string, double> myshopping("baking powder", 0.3);

    myrecipe.insert(myshopping);                        // copy insertion
    myrecipe.insert(make_pair<string, double>("eggs", 6.0)); // move insertion
    myrecipe.insert(mypantry.begin(), mypantry.end());  // range insertion
    myrecipe.insert({ {"sugar",0.8},{"salt",0.1} });    // initializer list insertion

    return 0;
}

(3)erase (delete)

#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;


int main()
{
    unordered_map<string, string> mymap;

    // populating container:
    mymap["U.S."] = "Washington";
    mymap["U.K."] = "London";
    mymap["France"] = "Paris";
    mymap["Russia"] = "Moscow";
    mymap["China"] = "Beijing";
    mymap["Germany"] = "Berlin";
    mymap["Japan"] = "Tokyo";
   
    // erase examples:
    mymap.erase(mymap.begin());      // erasing by iterator
    mymap.erase("France");             // erasing by key
    mymap.erase(mymap.find("China"), mymap.end()); // erasing by range


    return 0;
}

(4) clear (clear)

(5) swap (exchange)

3.5. Search 

(1) find (return iterator)

 unordered_map<int, string> m;
 m.emplace(make_pair(1, "yi"));
 m.emplace(make_pair(2, "er"));
    
 unordered_map<int, string>::iterator it = m.find(2);
 while (it != m.end())
 {
     cout << (*it).first << " " << (*it).second << endl;
     it++;
 }

(2) count (count)

 Generally not used in unordered_map, because the key value in unordered_map is unique

Generally used more in unordered_multimap

4. Traversal (iteration) of unordered_map

4.1. Iterator 

unordered_map<int, string>::iterator it = m.begin();
 while (it != m.end())
 {
     cout << (*it).first << " " << (*it).second << endl;
     it++;
 }

4.2. Scope for 

    for (auto e : m)
	{
		cout << e.first << " " << e.second << endl;
	}

Summarize

  1. The elements in unordered_map are key-value pairs
  2. The key in unordered_map is unique and cannot be modified
  3. unordered_map traversal is an unnecessary sequence
  4. The bottom layer of unordered_map is a hash structure
  5. Supports [ ] operator, insert search is actually performed in operator [ ]

Guess you like

Origin blog.csdn.net/weixin_74268082/article/details/134718525