Map <STL>

map的使用方法:

 

 1 #include <cstdio>
 2 #include <map>
 3 #include <string>
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     //声明int为键,const char* 为值
 9     map<int,const char*>m;
10 
11     //插入元素
12     m.insert(make_pair(1,"ONE"));
13     m.insert(make_pair(10,"TEN"));
14     m[100]="HUNDRED";
15 
16     //查找元素
17     map<int, const char*>::iterator ite;
18     ite = m.find(1);
19     puts(ite->second);  //输出ONE
20 
21     ite=m.find(2);
22     if(ite==m.end())   puts("not found");  //not found
23     else puts(ite->second);
24 
25     puts(m[10]);  //其他的写法
26 
27     //删除元素
28     m.erase(10);
29 
30     //遍历一遍所有元素
31     for(ite=m.begin();ite!=m.end();ite++){
32         printf("%d: %s\n",ite->first,ite->second);
33     }
34 }

 

posted @ 2016-03-06 16:30  Vmetrio  阅读(177)  评论(0编辑  收藏  举报