c++ map erase函数
时间: 2023-11-30 19:43:39 浏览: 63
C++中的map是一种关联式容器,它提供了一种将键映射到值的方法。erase()函数是map容器中的一个成员函数,用于删除map中的元素。以下是erase()函数的使用方法和示例:
1. erase()函数的使用方法:
```c++
map.erase(key); // 删除map中键为key的元素
map.erase(iterator); // 删除迭代器指向的元素
map.erase(first, last); // 删除[first, last)区间内的所有元素
```
2. erase()函数的示例:
```c++
#include <iostream>
#include <map>
using namespace std;
int main() {
map<int, int> b;
b[1] = 5;
b[2] = 6;
b[3] = 7;
b[4] = 8;
// 删除键为2的元素
b.erase(2);
// 删除键为奇数的元素
for (auto iter = b.begin(); iter != b.end();) {
if (iter->first % 2 == 1) {
iter = b.erase(iter);
} else {
++iter;
}
}
// 输出剩余元素
for (auto x : b) {
cout << x.first << " " << x.second << endl;
}
return 0;
}
```
输出结果为:
```
4 8
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)