C++ unordered_map删除
时间: 2023-10-12 14:07:47 浏览: 347
要删除C++中的unordered_map中的元素,你可以使用erase()函数。erase()函数接受一个迭代器作为参数,并删除该迭代器指向的键值对。
下面是一个示例代码,演示如何删除unordered_map中的元素:
```cpp
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, std::string> my_map = {{1, "one"}, {2, "two"}, {3, "three"}};
// 删除键为2的元素
my_map.erase(2);
// 遍历unordered_map并打印剩余的键值对
for (const auto& pair : my_map) {
std::cout << pair.first
相关问题
c++unordered_map count
unordered_map 是 C++ STL 中的一个关联容器,用于存储键值对。count 函数用于返回指定键在容器中出现的次数,因为 unordered_map 中每个键只能出现一次,所以 count 函数的返回值只能是 0 或 1。
下面是一个使用 unordered_map count 函数的示例代码:
```c++
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> myMap = {{"apple", 1}, {"banana", 2}, {"orange", 3}};
std::cout << "apple count: " << myMap.count("apple") << std::endl;
std::cout << "grape count: " << myMap.count("grape") << std::endl;
return 0;
}
```
输出结果为:
```
apple count: 1
grape count: 0
```
C++ unordered_map find
unordered_map 是 C++ STL 中的一个关联容器,用于存储键值对。可以使用 find() 函数在 unordered_map 中查找指定键是否存在。如果存在,则返回指向该键值对的迭代器;否则返回 unordered_map::end()。
示例代码:
```
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
unordered_map<string, int> mymap = {{"apple", 1}, {"banana", 2}, {"orange", 3}};
auto it = mymap.find("banana");
if (it != mymap.end()) {
cout << "banana is found, value is " << it->second << endl;
} else {
cout << "banana is not found" << endl;
}
return 0;
}
```
输出结果:
```
banana is found, value is 2
```
阅读全文
相关推荐















