c++中map的常见用法
时间: 2023-07-08 13:17:13 浏览: 54
在C++中,map是一个关联容器,它提供了一种将键值对关联起来的方法。map中的每个元素都是一个键值对,其中键是唯一的,可以通过键来访问值。以下是map的常见用法:
1. 插入元素
使用insert函数向map中插入一个键值对,如果map中已经存在该键,则会替换该键对应的值。
```c++
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> scores;
scores.insert(make_pair("Alice", 90));
scores.insert(make_pair("Bob", 80));
scores.insert(make_pair("Charlie", 70));
scores.insert(make_pair("Alice", 95)); // 替换Alice对应的值
return 0;
}
```
2. 删除元素
使用erase函数删除map中的一个元素,可以通过键来删除。
```c++
scores.erase("Alice");
```
也可以通过迭代器删除元素。
```c++
auto it = scores.find("Alice");
if (it != scores.end()) {
scores.erase(it);
}
```
3. 访问元素
使用[]运算符来访问map中的元素。
```c++
int score = scores["Alice"];
```
如果map中不存在该键,则会自动插入一个键为该值的键值对,并将值初始化为默认值。
```c++
int score = scores["David"]; // 自动插入一个键为David,值为默认值的键值对
```
4. 查找元素
使用find函数查找map中是否存在某个键。
```c++
auto it = scores.find("Alice");
if (it != scores.end()) {
int score = it->second;
}
```
5. 遍历元素
可以使用迭代器遍历map中的元素。
```c++
for (auto it = scores.begin(); it != scores.end(); ++it) {
string name = it->first;
int score = it->second;
}
```
以上是map的常见用法,希望对你有所帮助。