zoukankan      html  css  js  c++  java
  • 【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 }

     输出结果:

  • 相关阅读:
    北航2020OO第一单元博客作业
    OO第四单元总结
    OO第三单元总结
    OO第二单元总结
    OO第一单元总结
    北航2020年OO第四单元总结
    北航2020年OO第三单元总结
    北航2020年OO第二单元总结
    北航2020年OO第一单元总结
    面向对象第四单元总结
  • 原文地址:https://www.cnblogs.com/sunbines/p/10524448.html
Copyright © 2011-2022 走看看