李sir_Blog

博客园 首页 联系 订阅 管理
  705 随笔 :: 58 文章 :: 134 评论 :: 193万 阅读

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()程式碼都差不多長,所以沒有特別建議。

posted on   李sir  阅读(2224)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示