STL中map的使用
简介
map 是 STL 的一个关联容器,它提供一对一的数据处理能力。
map 对象是模板类,需要关键字和存储对象两个模板参数:其中第一个参数称为关键字,每个关键字只能在 map 中出现一次;第二个参数称为该关键字的值。可以将关键字和存储对象理解为“{键,值}对”。
map的数据插入操作
 |  mp.insert(pair<int,string>(3,"xingyuanjie"));
  mp[2]="wangzhouyang";
 
  | 
说明:上面的两种方法是有区别的,用 insert 函数插入数据,涉及到集合的唯一性这个概念,即当 map 中有这个关键字时,insert 操作是不能实现数据插入的;但是数组方式能够插入数据,插入的数据会覆盖该关键字之前对应的值。
map中数据的遍历
 | map<int,string>::iterator it;					 for (it=mp.begin();it!=mp.end();it++) {     cout<<it->first<<" "<<it->second<<endl; }
 
  | 
map中数据的查找
 | map<int,string>::iterator it;					 it=mp.find(1); if(it!=mp.end()){         cout << "Find it, the relative value is: " << it->second << endl; } else{        	cout << "Can not find the relative value." << endl; }
 
  | 
map中数据的删除
 | map<int,string>::iterator it;					 it = mp.find(2); mp.erase(it);
 
  | 
map中数据的排序
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 27 28 29 30 31 32 33 34
   | #include<bits/stdc++.h> using namespace std; map<int,string> mp; int main() {          mp.insert(pair<int,string>(3,"xingyuanjie"));     mp.insert(pair<int,string>(1,"shicheng"));     mp.insert(pair<int,string>(4,"tanghaipeng"));     mp.insert(pair<int,string>(6,"zhouyuhao"));     mp.insert(pair<int,string>(5,"heqichuan"));          mp[2]="wangzhouyang";          map<int,string>::iterator it;     for (it=mp.begin();it!=mp.end();it++) {         cout<<it->first<<" "<<it->second<<endl;     }          it=mp.find(1);     if(it!=mp.end()){         cout << "Find it, the relative value is: " << it->second << endl;     }     else {         cout << "Can not find the relative value." << endl;     }          it = mp.find(2);     mp.erase(it);     for (it=mp.begin();it!=mp.end();it++) {         cout<<it->first<<" "<<it->second<<endl;     }     return 0; }
 
  | 
程序输出:
 | 1 shicheng 2 wangzhouyang 3 xingyuanjie 4 tanghaipeng 5 heqichuan 6 zhouyuhao Find it, the relative value is: shicheng 1 shicheng 3 xingyuanjie 4 tanghaipeng 5 heqichuan 6 zhouyuhao
 
  | 
参考资料:
(20条消息) STL中map介绍_liitdar的博客-CSDN博客_stlmap