溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C++中的map容器如何使用

發(fā)布時間:2023-03-31 11:28:51 來源:億速云 閱讀:87 作者:iii 欄目:開發(fā)技術(shù)

這篇“C++中的map容器如何使用”文章的知識點大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“C++中的map容器如何使用”文章吧。

    一、map容器

    1.1 簡介

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

    ② pair中第一個元素為key(鍵值),起到索引作用,第二個元素為value(實值)。

    ③ 所有元素都會根據(jù)元素的鍵值自動排序。

    ④ map容器和multimap容器屬于關(guān)聯(lián)式容器,底層結(jié)構(gòu)是用二叉樹實現(xiàn)。

    ⑤ map容器可以根據(jù)key值快速找到value值。

    ⑥ map和multimap區(qū)別:

    • map不允許容器中有重復(fù)key值元素。

    • mutimap運行容器中有重復(fù)的key值元素。

    1.2 pair對組的創(chuàng)建

    ① 功能描述:成對出現(xiàn)的數(shù)據(jù),利用對組可以返回兩個數(shù)據(jù)。

    ② 兩種創(chuàng)建方式:

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

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

    ③ 兩種方式都可以創(chuàng)建對組,記住一種即可。

    #include<iostream>
    using namespace std;
    #include <set>
     
    //pair對組的創(chuàng)建
     
    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;
    }

    運行結(jié)果:

    姓名:Tom年齡:20
    姓名:Jerry年齡:30
    請按任意鍵繼續(xù). . .

    1.3 map容器構(gòu)造和賦值

    ① 功能描述:對map容器進行構(gòu)造和賦值操作。

    ② 構(gòu)造函數(shù):

    • map<T1,T2> mp; //map默認構(gòu)造函數(shù)

    • map(const map &mp); //拷貝構(gòu)造函數(shù)

    ③ 賦值操作:

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

    ④ map容器中所有元素都是成對出現(xiàn),插入元素時候需要使用對組。

    #include<iostream>
    using namespace std;
    #include <map>
     
    //map容器 構(gòu)造和賦值
     
    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()
    {
        //創(chuàng)建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);
     
        //拷貝構(gòu)造
        map<int, int>m2(m);
        printMap(m);
     
        //賦值
        map<int, int>m3;
        m3 = m2;
        printMap(m3);
    }
     
    int main() 
    {
        test01();
     
        system("pause");
     
        return 0;
    }

    運行結(jié)果:

    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
    請按任意鍵繼續(xù). . .

    1.4 map容器大小和交換

    ① 功能描述:統(tǒng)計map容器大小以及交換map容器。

    ② 函數(shù)原型:

    • size(); //返回容器中元素的數(shù)目。

    • 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()
    {
        //創(chuàng)建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;
    }

    運行結(jié)果:

    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
    請按任意鍵繼續(xù). . .

    1.5 map容器插入和刪除

    ① 功能描述:map容器進行插入數(shù)據(jù)和刪除數(shù)據(jù)。

    ② 函數(shù)原型:

    insert(elem); //在容器中插入元素。
    clear(); //清除所有元素。
    erase(pos); //刪除pos迭代器所指的元素,返回下一個元素的迭代器。
    erase(beg,end); //刪除區(qū)間[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()
    {
        //創(chuàng)建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]沒有數(shù),它會自動創(chuàng)建出一個value為0的數(shù)
        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;
    }

    運行結(jié)果:

    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
    請按任意鍵繼續(xù). . .

    1.6 map容器查找和統(tǒng)計

    ① 對map容器進行查找數(shù)據(jù)以及統(tǒng)計數(shù)據(jù)。

    ② 函數(shù)原型:

    find(key); //查找key是否存在,若存在,返回該鍵的元素的迭代器;若不存在,返回set.end();
    cout(key); //統(tǒng)計key的元素個數(shù)。
    #include<iostream>
    using namespace std;
    #include <map>
     
    void test01()
    {
        //創(chuàng)建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;
        }
     
        //統(tǒng)計
        //map不允許插入重復(fù)key元素,count統(tǒng)計而言 結(jié)果要么是0 要么是1
        //mutimap 的count統(tǒng)計可以大于1
        int num = m.count(3);
        cout << "num = " << num << endl;
    }
     
    int main() 
    {
        test01();
     
        system("pause");
        
        return 0;
    }

    運行結(jié)果:

    查到了元素 key = 3 value = 30
    num = 1
    請按任意鍵繼續(xù). . .

    1.7 map容器排序

    ① map容器默認排序規(guī)則為按照key值進行從小到大排序,利用仿函數(shù),可以改變排序規(guī)則。

    ② 利用仿函數(shù)可以指定map容器的排序規(guī)則。

    ③ 對于自定義數(shù)據(jù)類型,map必須要指定排序規(guī)則,同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()
    {
        //創(chuàng)建map容器
        //不是插了之后再排序,而是在創(chuàng)建的時候就排序
        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;
    }

    運行結(jié)果:

    key = 5 value = 50
    key = 4 value = 40
    key = 3 value = 30
    key = 2 value = 20
    key = 1 value = 10
    請按任意鍵繼續(xù). . .

    二、評委打分

    ① 案例描述:選手ABCDE,10個評委分別對每一名選手打分,去除最高分,去除評委中最低分,取平均分。

    ② 實現(xiàn)步驟:

    • 創(chuàng)建五名選手,放到vector容器中。

    • 遍歷vector容器,取出來每一個選手,執(zhí)行for循環(huán),可以把10個評委打分存到deque容器中。

    • sort算法對deque容器中分數(shù)進行排序,去除最高分和最低分。

    • deque容器遍歷一遍,累加總分。

    • 獲取平均分。

    #include <iostream>
    using namespace std;
    #include<vector> 
    #include<deque>
    #include<string>
    #include<algorithm>  //標(biāo)準(zhǔn)算法頭文件
    #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);
     
            //將創(chuàng)建的person對象,放入到容器中
            v.push_back(p);
        }
    }
     
    //2、給5名選手打分
    void setScore(vector<Person>& v)
    {
        for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)
        {
            //將評委的分數(shù)  放入到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; //累加每個評委的分數(shù)
            }
     
            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、創(chuàng)建5名選手
        vector<Person>v;  //存放選手容器
        createPerson(v);
     
        //測試
        for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)
        {
            cout << "姓名:" << (*it).m_Name << "分數(shù):" << (*it).m_Score << endl;
        }
     
        //2、給5名選手打分
        setScore(v);
     
        //3、顯示最后得分
        showScore(v);
     
        system("pause");
     
        return 0;
    }

    運行結(jié)果:

    姓名:選手A分數(shù):0
    姓名:選手B分數(shù):0
    姓名:選手C分數(shù):0
    姓名:選手D分數(shù):0
    姓名:選手E分數(shù):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
    請按任意鍵繼續(xù). . .

    三、年齡排序

    ① 案例描述:將Person自定義數(shù)據(jù)類型進行排序,Person中屬性有姓名、年齡、身高。

    ② 排序規(guī)則:按照年齡進行升序,如果年齡相同按照身高進行降序。

    #include<iostream>
    using namespace std;
    #include <list>
    #include<string>
    #include<algorithm>
     
    //list容器  排序案例 對于自定義數(shù)據(jù)類型 做排序
     
    //按照年齡進行升序 如果年齡相同 按照身高進行降序
     
    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;  //身高
    };
     
    //指定排序規(guī)則
    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; //創(chuàng)建容器
     
        //準(zhǔn)備數(shù)據(jù)
        Person p1("劉備", 35, 175);
        Person p2("劉備", 45, 180);
        Person p3("劉備", 50, 170);
        Person p4("劉備", 25, 190);
        Person p5("劉備", 35, 160);
        Person p6("劉備", 35, 200);
     
        //插入數(shù)據(jù)
        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(); 報錯,自定義數(shù)據(jù)類型編譯器不知道怎么排序
        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;
    }

    運行結(jié)果:

    姓名:劉備 年齡:35 身高:175
    姓名:劉備 年齡:45 身高:180
    姓名:劉備 年齡:50 身高:170
    姓名:劉備 年齡:25 身高:190
    姓名:劉備 年齡:35 身高:160
    姓名:劉備 年齡:35 身高:200
    排序后:
    姓名:劉備 年齡:25 身高:190
    姓名:劉備 年齡:35 身高:200
    姓名:劉備 年齡:35 身高:175
    姓名:劉備 年齡:35 身高:160
    姓名:劉備 年齡:45 身高:180
    姓名:劉備 年齡:50 身高:170
    請按任意鍵繼續(xù). . .

    四、 員工分組

    案例描述:

    • 公司今天招募了10個員工(ABCDEFGHIJ),10名員工進入公司之后,需要指派員工在那個部門工作。

    • 員工信息由:姓名 工資。部門為:策劃、美術(shù)、研發(fā)。

    • 隨機給10名員工分配部門和工資。

    • 通過multimap進行信息的插入。key(部門編號)value(員工)

    • 分部門顯示員工信息。

    實現(xiàn)步驟:

    • 創(chuàng)建10名員工,放到vector中

    • 遍歷vector容器,取出每個員工,進行隨機分組。

    • 分組后,將員工部門編號為key,具體員工作為value,放入到multimao容器中。

    • 分部門顯示員工信息。

    #include<iostream>
    using namespace std;
    #include <vector>
    #include <map>
    #include<string>
    #include<ctime>
     
    /*
    實現(xiàn)步驟:
    1. 創(chuàng)建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++)
        {
            //產(chǎn)生隨機部門編號
            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); //統(tǒng)計具體人數(shù)
        int index = 0;
        for (; pos != m.end() && index < count; pos++,index++)
        {
            cout << "姓名:" << pos->second.m_Name << "工資:" << pos->second.m_Salary << endl;
        }
     
        cout << "--------" << endl;
        cout << "美術(shù)部門:" << endl;
        pos = m.find(MEISHU);
        count = m.count(MEISHU); //統(tǒng)計具體人數(shù)
        index = 0;
        for (; pos != m.end() && index < count; pos++, index++)
        {
            cout << "姓名:" << pos->second.m_Name << "工資:" << pos->second.m_Salary << endl;
        }
     
        cout << "--------" << endl;
        cout << "研發(fā)部門:" << endl;
        pos = m.find(YANFA);
        count = m.count(YANFA); //統(tǒng)計具體人數(shù)
        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、創(chuàng)建員工
        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;
    }

    運行結(jié)果:

    策劃部門:
    姓名:員工B工資:11578
    姓名:員工D工資:11655
    姓名:員工G工資:16818
    姓名:員工J工資:12160
    美術(shù)部門:
    姓名:員工F工資:12782
    姓名:員工H工資:15815
    研發(fā)部門:
    姓名:員工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
    請按任意鍵繼續(xù). . .

    以上就是關(guān)于“C++中的map容器如何使用”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對大家有幫助,若想了解更多相關(guān)的知識內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道。

    向AI問一下細節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI