c++STL容器之map容器

时间:2022-07-24
本文章向大家介绍c++STL容器之map容器,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.map中所有的元素都是pair;

2.pair元素中第一个元素为key,第二个元素为value;

3.所有元素都会根据键值自动排序;

4.map中不允许有重复的键,multimap中允许有重复的键;

优点:可以根据key快速的找到value;

一、构造函数

map<T1,T2> mp;
map(const map &mp);

二、赋值

map& operator=(const map &mp);

三、map大小和交换

size();
empty();
swap(st);

四、插入和删除

insert(ele);
clear();
erase(pos);
erase(beg,end);
erase(key);
#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<int, int>m;

    //插入
    //第一种
    m.insert(pair<int, int>(1, 10));

    //第二种
    m.insert(make_pair(2, 20));

    //第三种
    m.insert(map<int, int>::value_type(3, 30));

    //第四种
    m[4] = 40;

    //[]不建议插入,用途 可以利用key访问到value
    //cout << m[4] << endl;
    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;
}

五、查找和统计

void test01()
{
    //查找
    map<int, int>m;
    m.insert(pair<int, int>(1, 10));
    m.insert(pair<int, int>(2, 20));
    m.insert(pair<int, int>(3, 30));
    m.insert(pair<int, int>(3, 40));

    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
    //multimap的count统计可能大于1
    int num = m.count(3);
    cout << "num = " << num << endl;
}

六、map排序(按升序排序)

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

class MyCompare
{
public:
    bool operator()(int v1,int v2) const
    {
        //降序
        return v1 > v2;
    }
};

//map容器 排序
void test01()
{
    map<int, int , MyCompare>m;

    m.insert(make_pair(1, 10));
    m.insert(make_pair(2, 20));
    m.insert(make_pair(5, 50));
    m.insert(make_pair(3, 30));
    m.insert(make_pair(4, 40));


    for (map<int, int, MyCompare>::iterator it = m.begin(); it != m.end(); it++)
    {
        cout << "key = " << it->first << " value = " << it->second << endl;
    }
}

int main() {

    test01();

    system("pause");

    return 0;
}

vs2019在重载operator()时需要用const修饰。