C++ 之关联容器 map

标准库定义了四种关联容器:map是其中之一(另外还有set、multimap、multiset)。map的元素以键-值(key-value),在学了顺序容器之后,再学习关联容器,就比较比较好理解了。

 

map类型,可以说是键-值对的集合,每一个键都与一个或多个值相关联。

利用它可以构造多钟函数:

map<string , int >   a;

map<char ,int>   b; 

map<srting ,char >  c;

map<int,vector<int> > d;       等等

关于使用map函数的一些基本操作,不想用文字去多废话,直接看程序吧;

有关   插入数据   使用迭代器   查找    删除   获取长度     的基本操作:

 1 #include<iostream>
 2 #include<map>
 3 using namespace std;
 4 int main(){
 5     map<int,int> m;
 6    //定义迭代器
 7     map<int,int>::iterator  mIter; 
 8     //插入数据方法1
 9     m.insert(pair<int,int> (1,20) );
10     m.insert(pair<int,int> (4,20) );
11     m.insert(pair<int,int> (5,20) );
12     //法2
13     m.insert(map<int,int>::value_type (7,6) );
14     //法3  类似数组
15     m[8]=9;
16     
17     //查找与清除,均是利用到健值
18     map<int,int>::iterator  a = m.find(1);
19     if(a!=m.end()){
20         m.erase(a);
21     }
22     for(mIter = m.begin();mIter!=m.end();mIter++)
23         cout<<mIter->first<<" "<<mIter->second<<endl;
24     //获取长度
25     cout<<m.size()<<endl;
26     return 0;
27 }

 

值得注意一点,关联容器会自己帮你排序,排序是根据key(键)的大小,这一点它比顺序容器要好用用一些,还有就是因为这个原因,你map里面所定义的key(键)一定是要可以比较大小的类型。

修改

 1 #include<iostream>
 2 #include<map>
 3 #include<string>
 4 using namespace std;
 5 int main(){  
 6     map<char ,string>  n;
 7     map<char ,string>::iterator it;
 8     map<char ,string>::value_type   num1('1',"xioaming");
 9     n.insert(num1);
10     n['2'] = "xiaoli";
11     //遍历修改,虽说只有俩元素
12     for(it=n.begin();it!=n.end();it++)
13     {
14             it->second="xiaoqiu";
15             cout<<it->first<<endl;
16                 cout<<it->second<<endl;
17     }
18             return 0;
19 }

 

最后在加上一个书本上的一个计算单词个数的程序

 1 #include <iostream>
 2 #include <map>
 3 #include <string>
 4 using namespace std;
 5 int main()
 6 {
 7     string s;
 8     map<string, int> counters;    
 9     while (cin >> s)   // 读取单词并且计数
10         ++counters[s];
11     for (map<string, int>::const_iterator it = counters.begin();it != counters.end(); ++it) {
12         cout << it->first << "\t" << it->second << endl;
13     }
14     return 0;
15 }

 

posted @ 2013-08-07 10:44  兰幽  阅读(308)  评论(0编辑  收藏  举报