<STL – 3> Dictionary map and multimap

1. Introduction

Introduction to map

Map is a standard Associative container. A map is a sequence of key-value pairs, that is, (key, value) pairs.

It provides fast retrieval capabilities based on key

The key value in the map is unique, and the elements in the dictionary are arranged in a certain order

Map can directly access the value corresponding to the key and supports the [] operator, such as map[key]=value (change the value corresponding to the key key to value

The difference between multimap and map: Map supports unique key values, and each key can only appear once; while in multimap, the same key can appear multiple times. Multimap does not support [] operator.

Features

map map_name; The container here is a key-value pair type, similar to a python dictionary

2. Commonly used functions

1. Default structure

①. map syntax

map container name;

②. multimap syntax

multimap container name;

Note:

Among them, key and value types can also use various pointer types or custom types

2. Construction and initialization of map container

There are three ways to insert map elements:
● Insert objects through pair: mapStu.insert(pair(key, value) );

● Insert objects through value_type: mapStu.insert(map::value_type(key, value) );

● Inserting values similar to subscript index: mapStu[key] = value;

①. Use pair for insert construction

Syntax: map.insert(…); //Insert elements into the container and return pair

map<int, string> mStu;//Build a map

//error demonstration
mStu.insert(pair(3,"nihao"))//Error, during the initialization of pair, a flag parameter is required

//Construct first and then pass in
pair<int, string> p (3, "nihao")
mStu.insert(p);

// Directly passed in, successful insertion
mStu.insert(pair<int, string>(6, "good"));//Correct

④. Insert elements through emplace

//Syntax: dictionary name.emplace(key, value);
map<int, string> mStu;

// Use emplace to insert new elements
mStu.emplace(1, "A"); // Insert key-value pair {1, "A"}
mStu.emplace(2, "B"); // Insert key-value pair {2, "B"}

//Replace existing key-value pair
mStu.emplace(1, "C"); // Will not replace because key 1 already exists

cout << mStu[1]; // Output "A"

③. Insert objects through value_type

//Syntax:
mStu.insert(map<key type, value type>::value_type(key, value));

//Directly initialize value and assign it
mStu.insert(map<int, string>::value_type(5, "hello"));

//Build value_type first and then pass it in
map<int, string>::value_type v (7, "Hello");
mStu.insert(v)

④. Insert objects through array assignment

//grammar : 
map name [key name] = value; // It is equivalent to overloading the square brackets, and the characteristics will be overwritten.

//example : 
mStu.insert(pair<int, string>(6, "good")); //Object has been inserted
mStu.insert(pair<int, string>(6, "bad")); //The bad insertion here fails, the value of 6 will not be overwritten, and an iterator pointing to the existing element will be returned
mStu[6] = "bad"; //The value of 6 is overwritten as bad here
Features:

map name [key] = value, as lvalue can change the value corresponding to the key
As an rvalue you can find the value corresponding to the key in the dictionary
Note: If the key you are looking for does not exist, a key-value pair will be automatically created, where the value defaults to ‘ ‘ strong>

Example:
string stu_name = mStu[10];//In summary, there is no key 10, here we create one
cout << stu_name << endl; //Output a ' ', empty character here

Summary: Method ③ is intuitive, but there are performance issues: if the key exists, modify it, if it does not exist, insert it

3. Functions related to map size

①. size()

Syntax:

Dictionary name.size(); // Return the number of elements

②. empty()

Syntax:

Dictionary name.empty(); // Determine whether the dictionary container is empty, if so, return 1. Otherwise, return 0
(Commonly used: !map.empty())

4. Deletion of elements in map

①. clear() (clear)

Syntax:

Dictionary name.clear() //Delete all elements

②. erase() (delete with return value)

Syntax 1:

Dictionary name.erase(left iterator, right iterator); //Delete all elements in the interval [left iterator, right iterator], Return the iterator of end()

Syntax 2:

Dictionary name.erase(iterator); // Delete the element pointed to by the iterator. After deletion, return the iterator of the next element

Syntax 3:

Dictionary name.erase(key); // Delete the key-value pair corresponding to the key in the dictionary container. After the deletion is successful, the number of deleted elements will be returned. If there are multiple elements, all key-value pairs equal to the given key key-value pairs

Note:

If it is a map, it is 1. In multimap, a value greater than 1 may be returned.

5. Sorting rules of elements in map

By default, the sorting rules of the elements in the map are arranged in ascending order, so elements with small key values will be sorted first

But the keys in multimap can be repeated, not necessarily in a specific order

6. Search for elements in map

①.find()

Syntax: Dictionary name.find(; )// Successfully returns the iterator corresponding to the found one. The iterator points to the pair. You can use ‘.’ after dereferencing it, or ** use the iterator directly. ->**Access the key-value pair in the pair pointed to by the iterator

, if failed, return the iterator dictionary name.end()

②.at()

Syntax: Dictionary name.(); // Successfully returns the value corresponding to the input key. If the key value does not exist, an out of range exception will be thrown.

Note: commonly used find() instead, through

if (p.second != mStu.end())
        cout << "euqle_range: first:" << p.first->first << " second:" << (p.second--)->second << endl;
else cout << "key not found" << endl;

③.count()

Syntax: dictionary name.count(); // Returns the number of pairs in the container whose key is keyElem

④. lower_bound()

Syntax: Dictionary name.lower_bound(elem); //Returns the iterator of the first >=elem element

⑤. upper_bound()

Syntax: dictionary name.upper_bound(elem); // Returns the iterator of the first >elem element

⑥. equal_range()

Syntax: Dictionary name.equal_range(elem); //Returns two iterators with upper and lower limits equal to elem in the container. The upper limit is a closed interval, and the lower limit is an open interval, such as [beg, end), Note that two iterators are returned, but they are encapsulated in a pair, so ①. auto, ②. Iterator type of two maps in a pair

Example:
#include <iostream>
#include <map>
using namespace std;

int main()
{<!-- -->
        map<int, string> mStu;
        //Insert 1-6
        mStu.emplace(1, "good");

        pair<int, string> p1(2, "bad");
        mStu.insert(p1);
        mStu.insert(pair<int, string>(3, "python"));

        mStu[4] = "hello";

        map<int, string>::value_type v1(5, "c");
        mStu.insert(v1);
        mStu.insert(map<int, string>::value_type(6, "people"));

        //Find 1-6
         map<int, string>::iterator it1 = mStu.find(1);//Note that the iterator is returned, the iterator points to the pair, and the piar stores a key and a value (or use ' after dereferencing .', or use iterator directly ->)
         string name2 = mStu.at(2);//at only returns the value corresponding to the found key
         int n = mStu.count(3);//Returns the number of pairs with the key 3, which can be used as a function to detect existence in map, and find the number of existing pairs in mlutimap
         map<int, string>::iterator it2 = mStu.lower_bound(4);//The first iterator greater than or equal to, here returns the iterator pointing to 4
         map<int, string>::iterator it3 = mStu.upper_bound(5);//The first iterator greater than, here returns the iterator pointing to 6
         pair<map<int, string>::iterator, map<int, string>::iterator> p = mStu.equal_range(6);//The returned pair stores two iterators, beg and end, so pair<>The type in the angle brackets is the iterator of the two maps
         //Coincidentally, the value 6 returned here and the iterator of the elements after 6
         
         //string name3 = mStu.at(7);//If it does not exist, an error will be reported
         //perror("at");

         cout << "find(1):" << "second : " << it1->second << "first : " <<it1->first<< endl;//first is the key, seconds is the value
         cout << "at(2): :" << name2 << endl;
         cout << "count(3) : " << n << endl;
         cout << "lower_bound: " << it2->second <<"first : " << it2->first << endl;//Here you can see where the two things are pointing.
         cout << "upper_bound: " << it3->second << "first : " <<it3->first<< endl;
         cout << "euqle_range: first:" << p.first->first << " second:" << (--p.second)->second << endl;//The return value of the equal_range function is a pair object. The first and second members are iterators, pointing to the starting and ending positions of the matched key range respectively.
         //Move the second image forward one bit and point to the same position as beg
         if (p.second != mStu.end()) {<!-- -->
                cout << "euqle_range: first:" << p.first->first << " second:" << (p.second--)->second << endl;
         }
         else {<!-- -->
                cout << "key not found" << endl;//This sentence is displayed at this time
         }
         return 0;
}

7. Exchange function in map

grammar :
Dictionary name.swap(mp); //Swap two collection containers

Example:
//Use the dictionary above
         map<int, string> m1;
         m1.insert(map<int,string>::value_type (0, "nan"));

         mStu.swap(m1);//As seen through monitoring, the size of m1 is 6 elements at this time, the size of mStu is one element, and the exchange is completed

syntaxbug.com © 2021 All Rights Reserved.