multiMap遍歷方法


 1 /*
 2     multimap中的三種遍歷方法
 3     multimap中如果沒有查找到相應元素,則返回的迭代器是依據該元素的排列順序該鍵應該插入的位置
 4     如果找不到,則方法一和方法二返回的兩個迭代器應該相等
 5 */
 6 #include <iostream>
 7 #include <map>
 8 #include <string>
 9 #include <utility>
10 
11 using namespace std;
12 
13 int main()
14 {
15     multimap<string, string> mulMap;
16     mulMap.insert(make_pair("魯迅", "朝花夕拾"));
17     mulMap.insert(make_pair("魯迅", "阿Q正傳"));
18     mulMap.insert(make_pair("魯迅", "野草"));
19     mulMap.insert(make_pair("羅貫中", "三國演義"));
20     mulMap.insert(make_pair("羅貫中", "隋唐志傳"));
21     mulMap.insert(make_pair("瓊瑤", "還珠格格"));
22     mulMap.insert(make_pair("瓊瑤", "情深深雨蒙蒙"));
23     typedef multimap<string, string>::iterator multiMapItor;
24     //方法一:推薦
25     
26     string author("魯迅");
27     cout << author << "的書籍有:" << endl;
28     pair<multiMapItor, multiMapItor> pos = mulMap.equal_range(author);
29     while(pos.first != pos.second)
30     {
31         cout << pos.first->second << endl;
32         ++pos.first;
33     }
34     cout << endl;
35     //方法二:
36     author.assign("羅貫中");
37     cout << author << "的書籍有:" << endl;
38     multiMapItor beg = mulMap.lower_bound(author);
39     multiMapItor end = mulMap.upper_bound(author);
40     while(beg != end)
41     {
42         cout << beg->second << endl;
43         ++beg;
44     }
45     cout << endl;
46     //方法三:不推薦
47     author.assign("瓊瑤");
48     cout << author << "的書籍有:" << endl;
49     typedef multimap<string, string>::size_type sz_type;
50     sz_type entries = mulMap.count(author);
51     multiMapItor itor = mulMap.find(author);
52     for(sz_type cnt = 0; cnt != entries; ++cnt)
53         cout << (itor++)->second << endl;
54 
55     system("pause");
56     return 0;
57 }

 


免責聲明!

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



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