目录
map和multimap
map提供优秀的一对一数据处理能力.
元素是由key和value两部分组成的队组.key是唯一的.
给定一个key,就能确定相对的value.
map也叫关联数组,只是索引的方式是key不是整数.
map是一个有序的不允许key重复的容器,默认为升序.
multimap是一个有序的允许key重复的容器,默认为升序.
其余map和multimap完全相同.
初始化,遍历
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
//创建一个空的map
map<int, string> m;
//直接赋值
map<int, string> m2 = {
{1,"a"},
{2,"b"},
{3,"c"}
};
//复制构造函数
map<int, string> m3(m2);
//使用迭代器赋值
map<int, string> m4(m3.begin(), m3.end());
//赋值构造函数
m = m4;
for (auto it = m.begin(); it != m.end(); ++it)
{
cout << it->first << " " << it->second << endl;
}
return 0;
}
pair类型
对组,故名知意可以保存两个数据成员,也就是存储的是一个键值对(一个key,一个value)
#include <iostream>
//pair的头文件大部分编译器下不加也可以(其实还没有遇到过需要加的)
#include <utility>
#include <vector>
using namespace std;
int main()
{
//保存两个int
pair<int, int> p = { 1,2 };
//存储一个int和一个string
pair<int, string> p2(2, "a");
//存储一个int和一个vector 匿名对象
pair<int, vector<int>> p3 = { 1,vector<int>{1} };
//对组之间可以关系运算大于小于等于等等
//key
cout << p.first << endl; //1
//value
cout << p.second << endl; //2
return 0;
}
增加元素
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<int, int> m;
//会自动进行排序
map<int, int> m2{
{ 4,44 },
{ 1,11 },
{ 3,33 },
{ 2,22 },
{ 5,55 },
};
//按照迭代器位置插入,返回指向这个元素的迭代器
auto it = m.insert(m.begin(), pair<int, int>(6, 66));
cout << it->first << " " << it->second