c++中std::map移除元素
时间: 2023-11-28 13:45:01 浏览: 103
Map (c++实现的简易map)
可以使用 `erase()` 成员函数来移除 `std::map` 中的元素。该函数接受一个键作为参数,并返回被移除元素的个数。如果该键不存在,则返回 0。以下是一个示例代码:
```c++
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> people {
{"Fred", 45},
{"Joan", 33},
{"Jill", 22}
};
std::string name{"Joan"};
int count = people.erase(name);
if (count) {
std::cout << name << " was removed." << std::endl;
} else {
std::cout << name << " was not found." << std::endl;
}
// 遍历 map
for (const auto& p : people) {
std::cout << std::setw(10) << std::left << p.first << " " << p.second << "\n";
}
return 0;
}
```
输出结果为:
```
Joan was removed.
Fred 45
Jill 22
```
阅读全文