【C++ Primer | 11】关联容器(一)

在multimap或multiset中查找元素

第二种方法解释:

 

 1 #include <iostream>
 2 #include <utility>
 3 #include <iterator>
 4 #include <functional>
 5 #include <algorithm>
 6 #include <map> 
 7 #include <set>
 8 #include <string>
 9 using namespace std;
10 
11 int main()
12 {
13     pair<string, int> p[] = { {"a", 1},
14                              {"c", 3},
15                              {"b", 2},
16                              {"d", 4},
17                              {"a", 6},
18                              {"a", 9} };
19     multimap<string, int> mm(begin(p), end(p));
20     for (auto q : mm)
21     {
22         cout << q.first << " " << q.second << endl;
23     }
24     //第一种方法 find+count
25     string search_item("a");
26     auto entries = mm.count(search_item);
27     auto iter = mm.find(search_item);
28     while (entries)
29     {
30         cout << iter->second << endl;
31         ++iter;
32         --entries;
33     }
34     //第二种方法:面向迭代器的解决方法
35     for (auto beg = mm.lower_bound(search_item), end = mm.upper_bound(search_item); beg != end; ++beg)
36     {
37         cout << beg->second << " ";
38     }
39     //第二种方法:利用equal_range函数
40     for (auto pos = mm.equal_range(search_item); pos.first != pos.second; ++pos.first)
41     {
42         cout << pos.first->second << " ";
43     }
44     system("pause");
45     return 0;
46 }

 输出结果:

 

posted @ 2019-03-13 17:10  苏格拉底的落泪  阅读(148)  评论(0编辑  收藏  举报