CPP Map container 学习

本文主要写法参考C++ STL函数库

map简介

map是STL(中文标准模板库)的一个关联容器。

  1. 可以将任何基本类型映射到任何基本类型。如int array[100]事实上就是定义了一个int型到int型的映射。
  2. map提供一对一的数据处理,key-value键值对,其类型可以自己定义,第一个称为关键字,第二个为关键字的值
  3. map内部是自动排序的

map的用法

必须引入包

1
#include <map>

map的定义

map<type1name, type2name> maps;//第一个是键的类型,第二个是值的类型

1
map<string, int> maps;

map容器内元素的访问

通过下标进行访问

maps[‘c’] = 5;

通过迭代器进行访问

map可以使用it -> first来访问键,使用it -> second访问值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <map>
#include <iostream>
using namespace std;
int main()
{
map<char,int> maps;
maps['a'] = 10;
maps['b'] = 20;
maps['c'] = 30;
for(map<char,int>::iterator it=mp.begin(); it!=mp.end(); it++)
{
cout<<it -> first<<" "<<it -> second<<endl;
}
return 0;
}

map的常用用法

  • maps.insert() 插入
1
2
3
4
5
6
7
8
9
10
11
12
// 定义一个map对象
map<int, string> m;

//用insert函数插入pair
m.insert(pair<int, string>(11, "kk"));

// 用insert函数插入value_type数据
m.insert(map<int, string>::value_type(22, "pp"));

// 用数组方式插入
m[12] = "dd";
m[34] = "ff";
  • maps.find() 查找一个元素
  • maps.clear() 清空
  • maps.erase() 删除一个元素
  • maps.size() 长度
  • maps.begin() 返回指向map头部的迭代器
  • maps.end() 返回指向map末尾的迭代器
  • maps.rbegin()返回指向map尾部的逆向迭代器
  • maps.rend() 返回指向map头部的逆向迭代器
  • maps.empty()判断其是否为空
  • maps.swap()交换两个map
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    map<string, int>::iterator it;

    it=maps.find("123");

    //迭代器刪除
    it = maps.find("123");
    maps.erase(it);

    //关键字删除
    int n = maps.erase("123"); //如果刪除了返回1,否则返回0

    //用迭代器范围刪除 : 把整个map清空
    maps.erase(maps.begin(), maps.end());
    //等同于maps.clear()

    int len = maps.size();获取到map中映射的次数

    //迭代
    map<string, int>::iterator it;
    for(it = maps.begin(); it != maps.end(); it++)
    cout<< it-> first<<" "<<itr -> second<<endl;//输出key 和value值

    //反向迭代
    map<string,int>::reverse_iterator it;
    for(it = maps.rbegin(); it != maps.rend(); it++)
    cout<<it -> first<<' '<<it -> second<<endl;

CPP Map container 学习
https://chaggle.github.io/2020/10/11/cpp/Map/
作者
chaggle
发布于
2020年10月11日
许可协议