C++中map容器的具体使用

一、map容器

1.1 简介

① map容器中的所有元素都是pair。

② pair中第一个元素为key(键值),起到索引作用,第二个元素为value(实值)。

③ 所有元素都会根据元素的键值自动排序。

④ map容器和multimap容器属于关联式容器,底层结构是用二叉树实现。

⑤ map容器可以根据key值快速找到value值。

⑥ map和multimap区别:

  • map不允许容器中有重复key值元素。
  • mutimap运行容器中有重复的key值元素。

1.2 pair对组的创建

① 功能描述:成对出现的数据,利用对组可以返回两个数据。

② 两种创建方式:

  • pair<type,type> p (value1, value2);
  • pair<type,type> p = make_pair(value1,value2);

③ 两种方式都可以创建对组,记住一种即可。

#include<iostream>
using namespace std;
#include <set>
 
//pair对组的创建
 
void test01()
{
    //第一种方式
 
    pair<string, int>p("Tom", 20);
 
    cout << "姓名:" << p.first << "年龄:" << p.second << endl;
 
    //第二种方式
 
    pair<string, int>p2 = make_pair("Jerry", 30);
    cout << "姓名:" << p2.first << "年龄:" << p2.second << endl;
}
 
int main() 
{
    test01();
 
    system("pause");
 
    return 0;
}

运行结果:

姓名:Tom年龄:20

姓名:Jerry年龄:30

请按任意键继续. . .

1.3 map容器构造和赋值

① 功能描述:对map容器进行构造和赋值操作。

② 构造函数:

  • map<T1,T2> mp; //map默认构造函数
  • map(const map &mp); //拷贝构造函数

③ 赋值操作:

  • map& operator=(const map &mp); //重载等号操作符

④ map容器中所有元素都是成对出现,插入元素时候需要使用对组。

#include<iostream>
using namespace std;
#include <map>
 
//map容器 构造和赋值
 
void printMap(map<int, int>& m)
{
    for (map<int,int>::iterator it = m.begin();it!=m.end();it++)
    {
        cout << "key = " << it->first << " value = " << it->second << endl;
    }
    cout << endl;
}
 
void test01()
{
    //创建map容器
    map<int, int>m;
 
    m.insert(pair<int, int>(1, 10));  //1为key;10为value
    m.insert(pair<int, int>(3, 30));
    m.insert(pair<int, int>(2, 20));
    m.insert(pair<int, int>(4, 40));
 
    printMap(m);
 
    //拷贝构造
    map<int, int>m2(m);
    printMap(m);
 
    //赋值
    map<int, int>m3;
    m3 = m2;
    printMap(m3);
}
 
int main() 
{
    test01();
 
    system("pause");
 
    return 0;
}

运行结果:

key = 1 value = 10

key = 2 value = 20

key = 3 value = 30

key = 4 value = 40

key = 1 value = 10

key = 2 value = 20

key = 3 value = 30

key = 4 value = 40

key = 1 value = 10

key = 2 value = 20

key = 3 value = 30

key = 4 value = 40

请按任意键继续. . .

1.4 map容器大小和交换

① 功能描述:统计map容器大小以及交换map容器。

② 函数原型:

  • size(); //返回容器中元素的数目。
  • empty(); //判断容器是否为空。
  • swap(st); //交换两个集合容器。
#include<iostream>
using namespace std;
#include <map>
 
void printMap(map<int, int>& m)
{
    for (map<int,int>::iterator it = m.begin();it!=m.end();it++)
    {
        cout << "key = " << it->first << " value = " << it->second << endl;
    }
    cout << endl;
}
 
//大小
void test01()
{
    //创建map容器
    map<int, int>m;
 
    m.insert(pair<int, int>(1, 10));  //1为key;10为value
    m.insert(pair<int, int>(3, 30));
    m.insert(pair<int, int>(2, 20));
 
    printMap(m);
 
    if (m.empty())
    {
        cout << "m为空" << endl;
    }
    else
    {
        cout << "m不为空" << endl;
        cout << "m的大小" << m.size() << endl;
    }
}
 
//交换
void test02()
{
    map<int, int>m1;
 
    m1.insert(pair<int, int>(1, 10));  //1为key;10为value
    m1.insert(pair<int, int>(3, 30));
    m1.insert(pair<int, int>(2, 20));
 
    map<int, int>m2;
 
    m2.insert(pair<int, int>(4, 100));  
    m2.insert(pair<int, int>(5, 300));
    m2.insert(pair<int, int>(6, 200));
 
    cout << "交换前:" << endl;
    printMap(m1);
    printMap(m2);
 
    m1.swap(m2);
    cout << "交换后:" << endl;
    printMap(m1);
    printMap(m2);
}
 
int main() 
{
    test01();
    test02();
 
    system("pause");
 
    return 0;
}

运行结果:

key = 1 value = 10

key = 2 value = 20

key = 3 value = 30

m不为空

m的大小3

交换前:

key = 1 value = 10

key = 2 value = 20

key = 3 value = 30

key = 4 value = 100

key = 5 value = 300

key = 6 value = 200

交换后:

key = 4 value = 100

key = 5 value = 300

key = 6 value = 200

key = 1 value = 10

key = 2 value = 20

key = 3 value = 30

请按任意键继续. . .

1.5 map容器插入和删除

① 功能描述:map容器进行插入数据和删除数据。

② 函数原型:

insert(elem); //在容器中插入元素。
clear(); //清除所有元素。
erase(pos); //删除pos迭代器所指的元素,返回下一个元素的迭代器。
erase(beg,end); //删除区间[beg,end)的所有元素,返回下一个元素的迭代器。
erase(key); //删除容器中值为key的元素。

③ map插入方式很多,记住其一即可。

#include<iostream>
using namespace std;
#include <map>
 
void printMap(map<int, int>& m)
{
    for (map<int,int>::iterator it = m.begin();it!=m.end();it++)
    {
        cout << "key = " << it->first << " value = " << it->second << endl;
    }
    cout << endl;
}
 
void test01()
{
    //创建map容器
    map<int, int>m;
 
    //第一种:
    m.insert(pair<int, int>(1, 10)); 
 
    //第二种:
    m.insert(make_pair(2, 10));
 
    //第三种:
    m.insert(map<int, int>::value_type(3, 30));  //map容器下为"值"为(3,30)
 
    //第四种:
    m[4] = 40;
 
    cout << m[5] << endl;  //由于没有m[5]没有数,它会自动创建出一个value为0的数
    cout << m[4] << endl;  //不建议用[]插入,但是可以利用key访问到value。
 
    printMap(m);
 
    //删除
    m.erase(m.begin());
    printMap(m);
 
    m.erase(3);  //安装key删除
    printMap(m);
 
    //清空方式一
    m.erase(m.begin(),m.end());  
    //清空方式二
    m.clear();
 
    printMap(m);
}
 
int main() 
{
    test01();
 
    system("pause");
 
    return 0;
}

运行结果:

0

40

key = 1 value = 10

key = 2 value = 10

key = 3 value = 30

key = 4 value = 40

key = 5 value = 0

key = 2 value = 10

key = 3 value = 30

key = 4 value = 40

key = 5 value = 0

key = 2 value = 10

key = 4 value = 40

key = 5 value = 0

请按任意键继续. . .

1.6 map容器查找和统计

① 对map容器进行查找数据以及统计数据。

② 函数原型:

find(key); //查找key是否存在,若存在,返回该键的元素的迭代器;若不存在,返回set.end();
cout(key); //统计key的元素个数。
#include<iostream>
using namespace std;
#include <map>
 
void test01()
{
    //创建map容器
    map<int, int>m;
 
    m.insert(pair<int,int>(1, 10));
    m.insert(pair<int, int>(3, 30));
    m.insert(pair<int,int>(2, 20));
    m.insert(pair<int, int>(3, 30));
 
    map<int,int>::iterator pos = m.find(3);
    
    if (pos != m.end())
    {
        cout << "查到了元素 key = " << (*pos).first << " value = " << pos->second << endl;
    }
    else
    {
        cout << "未找到元素" << endl;
    }
 
    //统计
    //map不允许插入重复key元素,count统计而言 结果要么是0 要么是1
    //mutimap 的count统计可以大于1
    int num = m.count(3);
    cout << "num = " << num << endl;
}
 
int main() 
{
    test01();
 
    system("pause");
    
    return 0;
}

运行结果:

查到了元素 key = 3 value = 30

num = 1

请按任意键继续. . .

1.7 map容器排序

① map容器默认排序规则为按照key值进行从小到大排序,利用仿函数,可以改变排序规则。

② 利用仿函数可以指定map容器的排序规则。

③ 对于自定义数据类型,map必须要指定排序规则,同set容器。

#include<iostream>
using namespace std;
#include <map>
 
class MyCompare
{
public:
    bool operator()(int v1, int v2)const
    {
        //降序
        return v1 > v2;
    }
};
 
void printMap(map<int, int, MyCompare>& m)
{
    for (map<int, int>::iterator it = m.begin(); it != m.end(); it++)
    {
        cout << "key = " << it->first << " value = " << it->second << endl;
    }
    cout << endl;
}
 
void test01()
{
    //创建map容器
    //不是插了之后再排序,而是在创建的时候就排序
    map<int, int, MyCompare>m;
 
    m.insert(make_pair(1, 10));
    m.insert(make_pair(2, 20));
    m.insert(make_pair(3, 30));
    m.insert(make_pair(4, 40));
    m.insert(make_pair(5, 50));
 
    printMap(m);
}
 
int main()
{
    test01();
 
    system("pause");
 
    return 0;
}

运行结果:

key = 5 value = 50

key = 4 value = 40

key = 3 value = 30

key = 2 value = 20

key = 1 value = 10

请按任意键继续. . .

二、评委打分

① 案例描述:选手ABCDE,10个评委分别对每一名选手打分,去除最高分,去除评委中最低分,取平均分。

② 实现步骤:

  • 创建五名选手,放到vector容器中。
  • 遍历vector容器,取出来每一个选手,执行for循环,可以把10个评委打分存到deque容器中。
  • sort算法对deque容器中分数进行排序,去除最高分和最低分。
  • deque容器遍历一遍,累加总分。
  • 获取平均分。
#include <iostream>
using namespace std;
#include<vector> 
#include<deque>
#include<string>
#include<algorithm>  //标准算法头文件
#include<ctime>
 
//选手类
class Person
{
public:
    Person(string name, int score)
    {
        this->m_Name = name;
        this->m_Score = score;
    }
 
    string m_Name;  //姓名
    int m_Score;    //平均分
};
 
void createPerson(vector<Person>& v)
{
    string nameSeed = "ABCDE";
    for (int i = 0; i < 5; i++)
    {
        string name = "选手";
        name += nameSeed[i];
 
        int score = 0;
        Person p(name, score);
 
        //将创建的person对象,放入到容器中
        v.push_back(p);
    }
}
 
//2、给5名选手打分
void setScore(vector<Person>& v)
{
    for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)
    {
        //将评委的分数  放入到deque容器中
        deque<int>d;
        for (int i = 0; i < 10; i++)
        {
            int score = rand() % 41 + 60;   // 60~100
            d.push_back(score);
        }
 
        cout << "选手:" << it->m_Name << "打分:" << endl;
        for (deque<int>::iterator dit = d.begin(); dit != d.end(); dit++)
        {
            cout << *dit << " ";
        }
        cout << endl;
 
        //排序
        sort(d.begin(), d.end());
 
        //去除最高分和最低分
        d.pop_back();
        d.pop_front();
 
        //取平均分
        int sum = 0;
        for (deque<int>::iterator dit = d.begin(); dit != d.end(); dit++)
        {
            sum += *dit; //累加每个评委的分数
        }
 
        int avg = sum / d.size();
 
        //将平均分 赋值给选手身上
        it->m_Score = avg;
    }
}
 
void showScore(vector<Person>&v)
{
    for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)
    {
        cout << "姓名:" << it->m_Name << "平均分" << it->m_Score << endl;
    }
}
 
int main()
{
    srand((unsigned int)time(NULL));
 
    //1、创建5名选手
    vector<Person>v;  //存放选手容器
    createPerson(v);
 
    //测试
    for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)
    {
        cout << "姓名:" << (*it).m_Name << "分数:" << (*it).m_Score << endl;
    }
 
    //2、给5名选手打分
    setScore(v);
 
    //3、显示最后得分
    showScore(v);
 
    system("pause");
 
    return 0;
}

运行结果:

姓名:选手A分数:0

姓名:选手B分数:0

姓名:选手C分数:0

姓名:选手D分数:0

姓名:选手E分数:0

选手:选手A打分:

87 90 93 71 96 67 60 83 64 73

选手:选手B打分:

88 72 66 97 62 90 93 95 100 63

选手:选手C打分:

63 85 71 63 92 64 89 90 89 98

选手:选手D打分:

98 61 62 76 62 74 90 65 85 68

选手:选手E打分:

87 67 96 60 75 63 92 76 98 75

姓名:选手A平均分78

姓名:选手B平均分83

姓名:选手C平均分80

姓名:选手D平均分72

姓名:选手E平均分78

请按任意键继续. . .

三、年龄排序

① 案例描述:将Person自定义数据类型进行排序,Person中属性有姓名、年龄、身高。

② 排序规则:按照年龄进行升序,如果年龄相同按照身高进行降序。

#include<iostream>
using namespace std;
#include <list>
#include<string>
#include<algorithm>
 
//list容器  排序案例 对于自定义数据类型 做排序
 
//按照年龄进行升序 如果年龄相同 按照身高进行降序
 
class Person
{
public:
    Person(string name, int age, int height)
    {
        this->m_Name = name;
        this->m_Age = age;
        this->m_Height = height;
    }
    string m_Name; //姓名
    int m_Age;     //年龄
    int m_Height;  //身高
};
 
//指定排序规则
bool comparePerson(Person &p1, Person &p2)
{
    //按照年龄 升序
    if (p1.m_Age == p2.m_Age)
    {
        //年龄相同 按照身高排序
        return p1.m_Height > p2.m_Height;
    }
    return p1.m_Age < p2.m_Age;
}
 
void test01()
{
    list<Person>L; //创建容器
 
    //准备数据
    Person p1("刘备", 35, 175);
    Person p2("刘备", 45, 180);
    Person p3("刘备", 50, 170);
    Person p4("刘备", 25, 190);
    Person p5("刘备", 35, 160);
    Person p6("刘备", 35, 200);
 
    //插入数据
    L.push_back(p1);
    L.push_back(p2);
    L.push_back(p3);
    L.push_back(p4);
    L.push_back(p5);
    L.push_back(p6);
 
    for (list<Person>::iterator it = L.begin(); it != L.end(); it++)
    {
        cout << "姓名:" << (*it).m_Name << " 年龄:" << it->m_Age << " 身高:" << it->m_Height << endl;
    }
 
    //排序
    cout << "---------------" << endl;
    cout << "排序后:" << endl;
 
    //L.sort(); 报错,自定义数据类型编译器不知道怎么排序
    L.sort(comparePerson);
    for (list<Person>::iterator it = L.begin(); it != L.end(); it++)
    {
        cout << "姓名:" << (*it).m_Name << " 年龄:" << it->m_Age << " 身高:" << it->m_Height << endl;
    }
}
 
 
int main()
{
    test01();
 
    system("pause");
 
    return 0;
}

运行结果:

姓名:刘备 年龄:35 身高:175

姓名:刘备 年龄:45 身高:180

姓名:刘备 年龄:50 身高:170

姓名:刘备 年龄:25 身高:190

姓名:刘备 年龄:35 身高:160

姓名:刘备 年龄:35 身高:200

排序后:

姓名:刘备 年龄:25 身高:190

姓名:刘备 年龄:35 身高:200

姓名:刘备 年龄:35 身高:175

姓名:刘备 年龄:35 身高:160

姓名:刘备 年龄:45 身高:180

姓名:刘备 年龄:50 身高:170

请按任意键继续. . .

四、 员工分组

案例描述:

  • 公司今天招募了10个员工(ABCDEFGHIJ),10名员工进入公司之后,需要指派员工在那个部门工作。
  • 员工信息由:姓名 工资。部门为:策划、美术、研发。
  • 随机给10名员工分配部门和工资。
  • 通过multimap进行信息的插入。key(部门编号)value(员工)
  • 分部门显示员工信息。

实现步骤:

  • 创建10名员工,放到vector中
  • 遍历vector容器,取出每个员工,进行随机分组。
  • 分组后,将员工部门编号为key,具体员工作为value,放入到multimao容器中。
  • 分部门显示员工信息。
#include<iostream>
using namespace std;
#include <vector>
#include <map>
#include<string>
#include<ctime>
 
/*
实现步骤:
1. 创建10名员工,放到vector中
2. 遍历vector容器,取出每个员工,进行随机分组。
3. 分组后,将员工部门编号为key,具体员工作为value,放入到multimao容器中。
4. 分部门显示员工信息。
*/
 
#define CEHUA 0
#define MEISHU 1
#define YANFA 2
 
class Worker
{
public:
    string m_Name;
    int m_Salary;
};
 
void createWorker(vector<Worker>&v)
{
    string nameSeed = "ABCDEFGHIJ";
    for (int i = 0; i < 10; i++)
    {
        Worker worker;
        worker.m_Name = "员工";
        worker.m_Name += nameSeed[i];
 
        worker.m_Salary = rand() % 10000 + 10000; //10000~19999
        //将员工放入到容器中
        v.push_back(worker);
    }
}
 
void setGroup(vector<Worker>&v,multimap<int,Worker>&m)
{
    for (vector<Worker>::iterator it = v.begin(); it != v.end(); it++)
    {
        //产生随机部门编号
        int depeId = rand() % 3;//0 1 2
        //将员工插入到分组中
        //key代表部门编号,value代表具体员工
        m.insert(make_pair(depeId, *it));
    }
}
 
void showWorkerByGourp(multimap<int,Worker>&m)
{
    
    //0 A B C 1 D E 2 F G
    cout << "策划部门:" << endl;
 
    multimap<int, Worker>::iterator pos = m.find(CEHUA);
    int count = m.count(CEHUA); //统计具体人数
    int index = 0;
    for (; pos != m.end() && index < count; pos++,index++)
    {
        cout << "姓名:" << pos->second.m_Name << "工资:" << pos->second.m_Salary << endl;
    }
 
    cout << "--------" << endl;
    cout << "美术部门:" << endl;
    pos = m.find(MEISHU);
    count = m.count(MEISHU); //统计具体人数
    index = 0;
    for (; pos != m.end() && index < count; pos++, index++)
    {
        cout << "姓名:" << pos->second.m_Name << "工资:" << pos->second.m_Salary << endl;
    }
 
    cout << "--------" << endl;
    cout << "研发部门:" << endl;
    pos = m.find(YANFA);
    count = m.count(YANFA); //统计具体人数
    index = 0;
    for (; pos != m.end() && index < count; pos++, index++)
    {
        cout << "姓名:" << pos->second.m_Name << "工资:" << pos->second.m_Salary << endl;
    }
}
 
int main()
{
    srand((unsigned int)time(NULL));
 
    //1、创建员工
    vector<Worker>vWorker;
    createWorker(vWorker);
 
    //2、员工分组
    //0号、1号、2号代表不同部门
    multimap<int, Worker>mWorker;
    setGroup(vWorker, mWorker);
 
    //3、分组显示员工
    showWorkerByGourp(mWorker);
 
    //测试
    cout << "--------" << endl;
    cout << "测试:" << endl;
    for (vector<Worker>::iterator it = vWorker.begin(); it != vWorker.end(); it++)
    {
        cout << "姓名:" << it->m_Name << " 工资:" << it->m_Salary << endl;
    }
 
    system("pause");
 
    return 0;
}

运行结果:

策划部门:

姓名:员工B工资:11578

姓名:员工D工资:11655

姓名:员工G工资:16818

姓名:员工J工资:12160

美术部门:

姓名:员工F工资:12782

姓名:员工H工资:15815

研发部门:

姓名:员工A工资:16686

姓名:员工C工资:10638

姓名:员工E工资:11730

姓名:员工I工资:17047

测试:

姓名:员工A 工资:16686

姓名:员工B 工资:11578

姓名:员工C 工资:10638

姓名:员工D 工资:11655

姓名:员工E 工资:11730

姓名:员工F 工资:12782

姓名:员工G 工资:16818

姓名:员工H 工资:15815

姓名:员工I 工资:17047

姓名:员工J 工资:12160

请按任意键继续. . .

原文地址:https://blog.csdn.net/peng_258/article/details/129778715