map是映射,联想高中数学知识,这东西其实就是“键值对”。一个东西对应另一个东西的意思。比如一个人对应一个学号,就可以定义一个字符串string类型的人为“键”
而学号int类型为“值”,如:map<string,int> m;
map会自动将所有的键值对按照键的大小从小到大的方式排序。
#include <iostream>
#include <map>
#include <string>
#include <cstdlib>
using namespace std;
int main(){
map<string,int> m;
m["hello"] = 2;
cout<<m["hello"]<<endl; //输出值
cout<<m["world"]<<endl; //默认为0
m["world"] = 3;
m[","] = 1;
// 用迭代器遍历,输出map中所有的元素,键用it->first获取,值用it->second获取
for(auto it = m.begin();it != m.end();it++)
cout<<it->first<<' '<<it->second<<endl;
//访问map中第一个元素,输出键值
cout<<m.begin()->first<<' '<<m.begin()->second<<endl;
//访问map中最后一个元素,输出键值
cout<<m.rbegin()->first<<' '<<m.rbegin()->second<<endl;
//输出map中所有元素的个数
cout<<m.size();
return 0;
}