map就是从键(key)到值(value)的映射。因为重载了【】运算符,map像是数组的“高级版”。map是键值对,⽐如⼀个⼈名对应⼀个学号,就可以定义⼀个字符串string类型的⼈名为“键”,学号int类型为“值”,如map<string, int> m;当然键、值也可以是其它变量类型~map会⾃动将所有的键值对按照键从⼩到⼤排序,以下是map中常⽤的⽅法:
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> n;
// 定义⼀个空的map m,键是string类型的,值是int类型的
n["hai"] = 2;
// 将key为"hai", value为2的键值对(key-value)存⼊map中
cout << m["hai"] << endl;
// 访问map中key为"hai"的value, 如果key不存在,则返回0
cout << m["word"] << endl;
n["word"] = 3;
// 将"word"键对应的值修改为3
n[","] = 1;
// 设⽴⼀组键值对,键为"," 值为1
// ⽤迭代器遍历,输出map中所有的元素,键⽤it->first获取,值⽤it->second获取
for (auto it = n.begin(); it != n.end(); it++) {
cout << it->first << " " << it->second << endl;
}
// 访问map的第⼀个元素,输出它的键和值
cout << n.begin()->first << " " << n.begin()->second << endl;
// 访问map的最后⼀个元素,输出它的键和值
cout << n.rbegin()->first << " " << n.rbegin()->second << endl;
// 输出map的元素个数
cout << n.size() << endl;
return 0;
}