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
4
Filename : MultiMapFindByKey.cpp
5
Compiler : Visual C++ 8.0 / ISO C++
6
Description : Demo how to find by key in multimap
7
Release : 12/16/2006 1.0
8
*/
9
#include <iostream>
10
#include <map>
11
#include <string>
12
13
using namespace std;
14
15
int main() {
16
typedef multimap<string, string> 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
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

除了使用count() + find()程式碼較多外,lower_bound()/upper_bound()和equal_range()程式碼都差不多長,所以沒有特別建議。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· 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工具