[C/C++] multimap查找一個key對應的多個value


在multimap中,同一個鍵關聯的元素必然相鄰存放。基於這個事實,就可以將某個鍵對應的值一一輸出。

1、使用find和count函數count函數求出某個鍵出現的次數,find函數返回一個迭代器,指向第一個擁有正在查找的鍵的實例。

2、使用lower_bound(key)和upper_bound(key)

      lower_bound(key)返回一個迭代器,指向鍵不小於k的第一個元素

      upper_bound(key)返回一個迭代器,指向鍵不大於k的第一個元素

3、使用equat_range(key)

      返回一個迭代器的pair對象,first成員等價於lower_bound(key),second成員等價於upper_bound(key)

 1 #include <iostream>
 2 #include <string>
 3 #include <map>
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     multimap<string,int> m_map;
 9     string s("中國"),s1("美國");
10     m_map.insert(make_pair(s,50));
11     m_map.insert(make_pair(s,55));
12     m_map.insert(make_pair(s,60));
13     m_map.insert(make_pair(s1,30));
14     m_map.insert(make_pair(s1,20));
15     m_map.insert(make_pair(s1,10));
16     //方式1
17     int k;
18     multimap<string,int>::iterator m;
19     m = m_map.find(s);
20     for(k = 0; k != m_map.count(s); k++,m++)
21         cout<<m->first<<"--"<<m->second<<endl;
22     //方式2
23     multimap<string,int>::iterator beg,end;
24     beg = m_map.lower_bound(s1);
25     end = m_map.upper_bound(s1);
26     for(m = beg; m != end; m++)
27         cout<<m->first<<"--"<<m->second<<endl;
28     //方式3
29     beg = m_map.equal_range(s).first;
30     end = m_map.equal_range(s).second;
31     for(m = beg; m != end; m++)
32         cout<<m->first<<"--"<<m->second<<endl;
33     return 0;
34 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM