Simple use of mutimap in C + +

Keywords: P4

The basic usage of mutimap is the same as that of map. The key in the key value pair in map is unique, and the key in mutimap can be repeated. Mutimap is also very common in reality, such as the relationship between departments and employees. Both the header files of mutimap and map are related containers, which need to access the elements through iterators. However, in mutimap, you need to use the count() function to get the number of keys, and use find() to sort the iterators, so that you can access the elements through the number of iterators and keys. , the code is as follows;

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

class Person
{
public:
    string m_name;
    int m_age;
};
int main()
{
    //Department and employee mapping
    Person p1, p2, p3, p4, p5;
    p1.m_name = "Zhang San";
    p1.m_age = 31;

    p2.m_name = "Zhang Si";
    p2.m_age = 32;

    p3.m_name = "Zhang Wu";
    p3.m_age = 33;

    p4.m_name = "Zhang Liu";
    p4.m_age = 34;

    p5.m_name = "Zhang Qi";
    p5.m_age = 35;

    multimap<string, Person> mp;
    mp.insert(make_pair("Sales Department",p1));
    mp.insert(make_pair("Sales Department", p2));
    mp.insert(make_pair("Development Department", p3));
    mp.insert(make_pair("Development Department", p4));
    mp.insert(make_pair("Finance Department", p5));

    //Query all personnel of Development Department
    int num = mp.count("Development Department");
    int i = 0;
    multimap<string, Person>::iterator iter_result = mp.find("Development Department");
    while(iter_result != mp.end() && i<num)
    {
        cout << iter_result->first << ":" << iter_result->second.m_name << endl;
        ++iter_result;
        ++i;
    }

    //Add "+ W" after the name of the person over 34“
    multimap<string, Person>::iterator iter = mp.begin();
    for (;iter != mp.end();++iter)
    {
        if(iter->second.m_age >= 34)
        {
            iter->second.m_name += "+W";
        }
    }

    cout << "The result is:" << endl;
    //ergodic
    for (iter = mp.begin(); iter != mp.end(); ++iter)
    {
        cout << iter->first << ":" << iter->second.m_name << endl;
    }
    system("pause");
}

Posted by dyconsulting on Tue, 31 Dec 2019 11:25:49 -0800