zoukankan      html  css  js  c++  java
  • 如何列出multimap中某個key的所有value? (C/C++) (STL)

    map和multimap都自帶find(),不需Generic Algorithm就可搜尋,事實上,當container和algorithm都提供方法時,應先考慮使用container自帶的方法,因為algorithm考慮到泛型,還需要經過iterator,但container自帶的方法卻是量身訂做的,所以執行速度較快。

    要列出multimap中某個key的所有value,有三種方式,此範例demo如何使用這三種方式。

     1/* 
     2(C) OOMusou 2006 http://oomusou.cnblogs.com
     3
     4Filename    : MultiMapFindByKey.cpp
     5Compiler    : Visual C++ 8.0 / ISO C++
     6Description : Demo how to find by key in multimap
     7Release     : 12/16/2006 1.0
     8*/

     9#include <iostream>
    10#include <map>
    11#include <string>
    12
    13using namespace std;
    14
    15int main() {
    16  typedef multimap<stringstring> AuthorBooks;
    17  AuthorBooks authorBooks;
    18
    19  authorBooks.insert(make_pair("Stanley B. Lippman""C++ Primer"));
    20  authorBooks.insert(make_pair("Stanley B. Lippman""Essentail C++"));
    21  authorBooks.insert(make_pair("Scott Meyers""Effective C++"));
    22  authorBooks.insert(make_pair("Andrei Alexandrescu""Modern C++ Design"));
    23
    24  string searchItem = "Stanley B. Lippman";
    25
    26  // Find all values by key using count & find 
    27  AuthorBooks::size_type entries = authorBooks.count(searchItem);
    28  AuthorBooks::iterator iter = authorBooks.find(searchItem);
    29  for(AuthorBooks::size_type cnt = 0; cnt != entries; ++cnt) 
    30    cout << iter++->second << endl;
    31
    32  cout << endl;
    33  cout << endl;
    34
    35  // Find all values by key using lower_bound(), upper_bound();
    36  AuthorBooks::iterator beg = authorBooks.lower_bound(searchItem);
    37  AuthorBooks::iterator end = authorBooks.upper_bound(searchItem);
    38
    39  while(beg != end) 
    40    cout << beg++->second << endl;
    41
    42  cout << endl;
    43  cout << endl;
    44
    45  // Find all values by key using equal_range()
    46  typedef AuthorBooks::iterator iterAB;
    47  pair<iterAB, iterAB> pos = authorBooks.equal_range(searchItem);
    48  while(pos.first != pos.second) 
    49    cout << pos.first++->second << endl;
    50
    51  return 0;
    52}


    除了使用count() + find()程式碼較多外,lower_bound()/upper_bound()和equal_range()程式碼都差不多長,所以沒有特別建議。

  • 相关阅读:
    maven(一)maven自带的插件
    Faster RCNN 的细节补充
    leetcode 287
    一句话介绍python线程、进程和协程
    C++中指针和引用的区别
    C++ operator new和new operator的区别
    Faster RCNN算法训练代码解析(3)
    Faster RCNN算法训练代码解析(2)
    Faster RCNN算法训练代码解析(1)
    Faster RCNN算法demo代码解析
  • 原文地址:https://www.cnblogs.com/lzjsky/p/1861857.html
Copyright © 2011-2022 走看看