[C++21 day development plan] Mapping class-quick start STL map and multimap (Day17)

Hello everyone! I am [AI bacteria], a programmer who loves to play guitar. Me 热爱AI、热爱分享、热爱开源! This blog is my summary and reflection on learning. If you are also 深度学习、机器视觉、算法、Python、C++interested, you can focus on my dynamic, we learn together and progress together -
my blog address is: [AI] bacteria of blog
my Github project address is: [AI] of bacteria Github


1. Introduction to STL map class

map and multimap are key-value pair containers that support searching based on keys, similar to the dictionary class in the data structure.

Both map and multimup are template classes. The difference between them is that multimap can store duplicate keys, while the former can only store unique keys.

In order to achieve fast search, the internal structure of map and multimap looks like a binary tree . This means that when inserting elements in map and multimap, they will be sorted . It also means that other elements cannot be used to replace elements at a given position like a vector. An element at a specific position in the map cannot be replaced with a new element with a different value. This is because the map will compare the new element with other elements in the binary tree. , And then put it in another location.

In addition, it should be noted that when using STL map and multimap classes, you need to include the header file:

# include<map>

Insert picture description here

2. Basic operations of map and multimap classes

2.1 Instantiation operation

The typical map instantiation syntax is as follows:

map <keyType, valueType, Predicate=std::less <keyType> > mapObject;
multimap <keyType, valueType, Predicate=std::greater <keyType> >mmapObject;
  • The first parameter keyType represents the type of key
  • The second parameter valueType represents the type of value
  • The third parameter less/greater is used as a sorting criterion . Less is sorting in ascending order, and greater is sorting in descending order.

The following uses several different methods to instantiate a map or multimap of the key-value pair {string, int} type.

#include <iostream>
#include <map>
#include <string>

using namespace std;
template<typename KeyType>

int main()
{
    
    
	// 方法1
    map<int, string> map1;
    multimap<int, string> mmap1;
	// 方法2
    map<int, string> map2(map1);
    multimap<int, string> mmap2(mmap1);
	// 方法3
    map<int, string> map3(map1.cbegin(), map1.cend());
    multimap<int, string> mmap3(mmap1.cbegin(), mmap1.cend());    

    return 0;
}

2.2 Two sorting methods

In the process of instantiating map and multimap, if no sorting predicate is specified, map will sort the elements in ascending order by default .

To customize the sorting criteria of the map, we can use the following two methods:

(1) Use the predicates less and greater provided by the map class to determine the sorting criteria

// 1.升序 
map<int, string, less<int>> map1;
// 2.降序
multimap<int, string, greater<int>> mmap1;

(2) Custom predicates are used as sorting criteria

#include <iostream>
#include <map>
#include <string>

using namespace std;
template<typename KeyType>

// 自定义词谓
struct ReverseSort
{
    
    
    bool operator()(const KeyType& key1, const KeyType& key2)
    {
    
    
        return (key1 > key2);
    }
};

int main()
{
    
    
	// 实例化
    map<int, string> map1;
    multimap<int, string> mmap1;
    
	// 降序排列
    map<int, string, ReverseSort<int>> map5(map1.cbegin(), map1.cend());
    multimap<int, string, ReverseSort<int>> mmap5(mmap1.cbegin(), mmap1.cend());
    
    return 0;
}

3. Member functions of map and multimap classes

2.1 Insert element function insert()

Using the map member function insert(), you can insert new key-value pairs into the map; the following demonstrates 4 common insertion methods:

#include <iostream>
#include <map>
#include <string>

using namespace std;
template <typename T>

// 显示内容
void DisplayContents(const T& Input)
{
    
    
    for(auto iElement = Input.cbegin(); iElement != Input.cend(); ++iElement)
        cout<<iElement->first<<"  "<<iElement->second<<endl;
    cout<<endl;
}

int main()
{
    
    
    map<int, string, less<int>>map1;
    // 插入方法1
    map1.insert(map<int, string>::value_type(3, "Three"));
    // 插入方法2
    map1.insert(make_pair(1, "One"));
    // 插入方法3
    map1.insert(pair<int, string>(10, "Ten"));
  
    // 插入方法4,采用类似于数组的语法进行插入。
    map1[8] = "Eight";

    cout<<"键 :值"<<endl;
    DisplayContents(map1);

    return 0;
}

After four insertions of the class, there are four key-value pairs in the map, as shown below:

Insert picture description here

2.2 Find the element function find()

map and multimap provide the member function find(), which can find a value based on a given key .

What find() returns is an iterator, as shown below:

map1 <int, string>::const_iterator iFound = map1.find(Key);

When using find() to find an element, first check the iterator to ensure that find() is successful, and then use it to access the found value :

if(iFound != map1.end())
{
    
    
	cout<<"键 :值"<<endl;
	cout<<iFound->first<<" "<<iFound->second<<endl;
}
else
	cout<<"Key不存在于map中!"<<endl;

The following shows a practical example, using the member function find() to find the value corresponding to the key in map1:

#include <iostream>
#include <map>
#include <string>

using namespace std;
template <typename T>

// 显示内容
void DisplayContents(const T& Input)
{
    
    
    for(auto iElement = Input.cbegin(); iElement != Input.cend(); ++iElement)
        cout<<iElement->first<<"  "<<iElement->second<<endl;
    cout<<endl;
}

int main()
{
    
    
    map<int, string, less<int>>map1;
    // 插入元素
    map1.insert(make_pair(8, "Eight"));
    map1.insert(make_pair(1, "One"));
    map1.insert(make_pair(6, "Six"));
    map1.insert(make_pair(10, "Ten"));
    // 显示键值
    cout<<"键 :值"<<endl;
    DisplayContents(map1);
    // 根据键查找其对应的值
    auto iFound = map1.find(8);
    if(iFound != map1.end())
        cout<<iFound->first<<"对应的值是:"<<iFound->second<<endl;
    else
        cout<<"Key不存在于map1中!"<<endl;

    return 0;
}

The results are as follows:
Insert picture description here
If you are using a multimap, the container may contain multiple key-value pairs with the same key , so you need to find all the values corresponding to the specified key . Therefore, first use count() to determine how many values ​​correspond to the specified key, and then increment the iterator to access all the corresponding values.

There are 3 identical key-value pairs in the following map. The line needs to find the key-value pairs and output them in turn:

#include <iostream>
#include <map>
#include <string>

using namespace std;
template <typename T>

// 显示内容
void DisplayContents(const T& Input)
{
    
    
    for(auto iElement = Input.cbegin(); iElement != Input.cend(); ++iElement)
        cout<<iElement->first<<"  "<<iElement->second<<endl;
    cout<<endl;
}

int main()
{
    
    
    multimap<int, string, less<int>>map1;
    // 插入元素
    map1.insert(make_pair(8, "Eight"));
    map1.insert(make_pair(1, "One"));
    map1.insert(make_pair(8, "Eight"));
    map1.insert(make_pair(8, "Eight"));
    
    // 显示键值
    cout<<"键 :值"<<endl;
    DisplayContents(map1);

    // 根据键查找其所有对应的值
    auto iFound = map1.find(8);
    if(iFound != map1.end())
    {
    
    
        // 统计multimap中键8出现的次数
        size_t num = map1.count(8);
        for(size_t nCounter=0; nCounter<num; ++nCounter)
        {
    
    
            cout<<"Key: "<<iFound->first<<", Val["<<nCounter<<"]="<<iFound->second<<endl;
            ++iFound;
        }
    }
    else
        cout<<"Element Not Found In The Map!";

    return 0;
}

operation result:
Insert picture description here

2.3 Delete element function erase()

map and multimap provide the member function erase(), which is used to delete elements in the container. There are three main methods:

  • When a key is used as a parameter, this will delete all key-value pairs containing the specified key
map1.erase(key);
  • Take the iterator as the parameter, delete the parameter pointed to by the iterator
map1.erase(iFound);
  • Use the iterator to specify the boundary and delete all elements in the specified range
map1.erase(iLowerBound, iUpperBound);

The following is a practical demonstration of the use of the above three methods:

#include <iostream>
#include <map>
#include <string>

using namespace std;
template <typename T>

// 显示内容
void DisplayContents(const T& Input)
{
    
    
    for(auto iElement = Input.cbegin(); iElement != Input.cend(); ++iElement)
        cout<<iElement->first<<"  "<<iElement->second<<endl;
    cout<<endl;
}

int main()
{
    
    
    multimap<int, string, less<int>>map1;
    // 插入元素
    map1.insert(make_pair(8, "Eight"));
    map1.insert(make_pair(1, "One"));
    map1.insert(make_pair(6, "Six"));
    map1.insert(make_pair(10, "Ten"));
    map1.insert(make_pair(15, "Fifteen"));


    // 显示键值
    cout<<"键 :值"<<endl;
    DisplayContents(map1);

    // 删除键1对应的键值对
    map1.erase(1);
    cout<<"删除键1对应的键值对后:"<<endl;
    DisplayContents(map1);

    // 删除迭代器指向的元素
    auto iFound = map1.find(8);
    map1.erase(iFound);
    cout<<"删除键8对应的键值对后:"<<endl;
    DisplayContents(map1);

    // 删除指定范围内(6至10)的元素
    map1.erase(map1.lower_bound(6), map1.lower_bound(15));
    cout<<"删除指定范围内(从6开始,到15之前)的元素:"<<endl;
    DisplayContents(map1);

    return 0;
}

operation result:
Insert picture description here


Today’s sharing is over, I hope it will be helpful to your study!

Insert picture description here

Finally, I was fortunate to be selected into the CSDN original blog contest Top50, if you can vote for me, it will be the greatest encouragement to my creation! After voting, you can still participate in the official lottery!

Voting channel: CSDN original blog contest
Insert picture description here

Develop a habit, like first and then watch! Your support is the biggest motivation for my creation!

Guess you like

Origin blog.csdn.net/wjinjie/article/details/108710213