STL中的multimap---顺便说说如何查找同一关键字对应的所有值

来源:互联网 发布:捕食者算法 编辑:程序博客网 时间:2024/06/07 03:58

转载:http://blog.csdn.net/stpeace/article/details/44984639


我个人感觉哈, map的应用场景比multimap更多, 不过, 我们还是来学一下multimap。 我们知道, multimap中, 一个关键字可能对应多个不同的值, 怎么获取呢?我们来看程序, 接招(介绍三种方法):


      结果为:

[cpp] view plain copy
  1. #pragma warning(disable : 4786)  
  2. #include <map>  
  3. #include <string>  
  4. #include <iostream>  
  5. using namespace std;  
  6.   
  7. int main()  
  8. {  
  9.     multimap<int, string> mp;  
  10.     mp.insert(pair<int, string>(3, "hehe"));  
  11.     mp.insert(pair<int, string>(4, "haha"));  
  12.     mp.insert(pair<int, string>(2, "error"));  
  13.     mp.insert(pair<int, string>(3, "good"));  
  14.     mp.insert(pair<int, string>(3, "ok"));  
  15.     mp.insert(pair<int, string>(3, "hehe"));  
  16.   
  17.     multimap<int, string>::iterator it;  
  18.     for(it = mp.begin(); it != mp.end(); it++)  
  19.     {  
  20.         cout << it->first << "--->";  
  21.         cout << it->second << endl;  
  22.     }  
  23.   
  24.     // 方法一  
  25.     int n = mp.count(3); // 3的个数  
  26.     cout << n << endl;  
  27.   
  28.     int i = 0;  
  29.     it = mp.find(3); // 第一个3的位置  
  30.     for(i = 0; i < n; i++)  
  31.     {  
  32.         cout << it->first << "--->";  
  33.         cout << it->second << endl;  
  34.         it++; // 所有的3必然是相连的  
  35.     }  
  36.   
  37.     cout << "---------------------------" << endl;  
  38.   
  39.     // 方法二:  
  40.     for(it = mp.lower_bound(3); it != mp.upper_bound(3); it++)  
  41.     {  
  42.         cout << it->first << "--->";  
  43.         cout << it->second << endl;  
  44.     }  
  45.   
  46.     cout << "---------------------------" << endl;  
  47.   
  48.     // 方法三:  
  49.     pair<multimap<int, string>::iterator, multimap<int, string>::iterator > pos;  
  50.     for(pos = mp.equal_range(3); pos.first != pos.second; pos.first++)  
  51.     {  
  52.         cout << pos.first->first << "--->";  
  53.         cout << pos.first->second << endl;  
  54.     }  
  55.   
  56.     return 0;  
  57. }  
      结果为:

2--->error
3--->hehe
3--->good
3--->ok
3--->hehe
4--->haha
4
3--->hehe
3--->good
3--->ok
3--->hehe
---------------------------
3--->hehe
3--->good
3--->ok
3--->hehe
---------------------------
3--->hehe
3--->good
3--->ok
3--->hehe
Press any key to continue

阅读全文
0 0