Skip to content

Commit 9b6bcc2

Browse files
Create 2023-11-04-cpp-map.md
add cpp-map
1 parent 5d3176e commit 9b6bcc2

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
---
2+
layout: post
3+
title: "cpp中map根据key取value有几种方法"
4+
date: 2023-11-04 00:00:00 +0800
5+
categories: [cpp, map]
6+
---
7+
8+
## QuickStart
9+
10+
- `find()`
11+
12+
```cpp
13+
std::map<int, std::string> m;
14+
m.insert({5, "hello"});
15+
auto it = m.find(5);
16+
if (it != m.end()) {
17+
std::cout << it->second << std::endl; // 输出 "hello"
18+
} else {
19+
std::cout << "Key not found" << std::endl;
20+
}
21+
```
22+
23+
## Detail
24+
25+
在C++中,std::map是一个关联容器,它包含了key-value对。我们可以通过多种方法根据key来获取对应的value。以下是一些常用的方法:
26+
27+
1. `operator[]`:这是最简单的方法。如果我们知道要查找的key,那么只需使用数组运算符就可以直接访问该key对应的value。例如:
28+
29+
```cpp
30+
std::map<int, std::string> m;
31+
m[5] = "hello";
32+
std::cout << m[5] << std::endl; // 输出 "hello"
33+
```
34+
35+
> 注意,如果key不存在,使用operator[]将会插入一个新的元素,其key为所给定的key,value为默认值(对于int类型,是0;对于string类型,是空字符串)。
36+
37+
2. `at()`:这个方法也可以用来根据key获取value。但是,如果key不存在,它会抛出一个std::out_of_range异常。例如:
38+
39+
```cpp
40+
std::map<int, std::string> m;
41+
m.insert({5, "hello"});
42+
try {
43+
std::cout << m.at(5) << std::endl; // 输出 "hello"
44+
} catch(const std::out_of_range& e) {
45+
std::cerr << e.what() << std::endl;
46+
}
47+
```
48+
49+
3. `find()`:这个方法返回一个指向找到的元素的迭代器。如果元素不存在,它将返回指向容器尾部的迭代器。我们可以使用这个迭代器来检查元素是否存在,以及获取其value。例如:
50+
51+
```cpp
52+
std::map<int, std::string> m;
53+
m.insert({5, "hello"});
54+
auto it = m.find(5);
55+
if (it != m.end()) {
56+
std::cout << it->second << std::endl; // 输出 "hello"
57+
} else {
58+
std::cout << "Key not found" << std::endl;
59+
}
60+
```
61+
62+
4. `count()`:这个方法返回一个整数,表示有多少个元素具有给定的key。如果key不存在,返回值为0。例如:
63+
64+
```cpp
65+
std::map<int, std::string> m;
66+
m.insert({5, "hello"});
67+
if (m.count(5) > 0) {
68+
std::cout << m[5] << std::endl; // 输出 "hello"
69+
} else {
70+
std::cout << "Key not found" << std::endl;
71+
}
72+
```

0 commit comments

Comments
 (0)