[STL Notes, 2] Container: map

Article Directory

1 Overview

Baidu Encyclopedia summary content is as follows:

Mapping and multi-mapping provide fast and efficient retrieval of data of type T based on the existence of a key set of a certain type of Key. For a map, a key simply refers to a member stored in the container. Map does not support duplicate keys, but multimap supports duplicate keys. Map and multimap objects contain keys and values ​​related to each key. The data types of keys and values ​​are different, which is different from set. The key and value in the set are of the Key type, while the key and value in the map are two components in a pair structure.

add header file

#include <map>

General constructor initialization

    map<string,int> m1=
    {
    
    
        {
    
    "one",1},
        {
    
    "two",2},
        {
    
    "three",3},
    };

2 common operations

The first thing to do is to traverse the map

    for(auto iter = m1.begin();iter!=m1.end();++iter)
    {
    
    
        cout << iter->first << " "<< iter->second << endl;
    }

modified to print function

void printMap( map<string,int> &m1)
{
    
    
    for(auto iter = m1.begin();iter!=m1.end();++iter)
    {
    
    
        cout << iter->first << " "<< iter->second << endl;
    }
}

The printed results are as follows:

one 1
three 3
two 2

The way to insert is as follows:


    m1.insert(pair<string,int>("four",4));

Find the value corresponding to the corresponding key value. If the value does not exist, it will return 0 by default.

    cout << "five " << m1.find("five")->second << endl;
    cout << "one " << m1.find("one")->second << endl;

count is used to count the number of occurrences of key values. Since there are no repeated elements in the map, the calculation results are only 0 and 1

The following demo code shows:


    map<string,int> m1=
    {
    
    
        {
    
    "one",1},
        {
    
    "two",2},
        {
    
    "three",3},
        {
    
    "one",5},
    };
    m1.insert(pair<string,int>("four",4));
    cout << "one " << m1.find("one")->second << endl;
    cout << m1.count("one") << endl;
    printMap(m1);

The printed results are as follows:

one 1
1
four 4
one 1
three 3
two 2

size() is used to count the size of the current container. Like other containers of vector, do not elaborate too much

empty() is used to judge empty, 1 is empty, 0 is non-empty.

erase() is used to erase the content of the corresponding key value.

    m1.erase("one");

map overloads the operator [], and you can use this [key] to quickly access the value corresponding to the key value


    int num = m1["three"];

clear ( ) ; used to delete all elements in the container

Guess you like

Origin blog.csdn.net/qq_38753749/article/details/130217310