C++哈希表怎么删除元素
时间: 2024-06-18 14:06:10 浏览: 17
C++中的哈希表可以使用STL库中的unordered_map实现,可以使用erase()函数来删除元素。erase()函数接受一个迭代器参数,可以通过迭代器来删除指定位置的元素,也可以通过键来删除元素。例如:
```c++
#include <iostream>
#include <unordered_map>
int main()
{
std::unordered_map<int, std::string> myMap = {{1, "apple"}, {2, "banana"}, {3, "orange"}};
// 删除键为2的元素
myMap.erase(2);
// 删除迭代器指向的元素
auto it = myMap.find(1);
if (it != myMap.end()) {
myMap.erase(it);
}
// 输出剩余元素
for (const auto& p : myMap) {
std::cout << "Key: " << p.first << ", Value: " << p.second << std::endl;
}
return 0;
}
```
上述代码中,使用erase()函数删除了键为2的元素和迭代器指向的键为1的元素,最终输出剩余的元素。
相关问题
c++哈希表删除元素
C语言中的哈希表删除元素可以使用unordered_map的erase()函数进行操作。该函数接受一个参数,即要删除的元素的键值。具体操作步骤如下:
1. 首先,包含头文件#include <unordered_map>。
2. 创建一个unordered_map对象,并向其中插入键值对。
3. 使用erase()函数删除指定的元素。该函数接受一个参数,即要删除的元素的键值。
4. 最后,可以通过遍历unordered_map对象,验证元素是否已删除。
下面是一个示例代码:
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, std::string> hashMap;
hashMap.insert({1, "aaa"});
hashMap.insert({2, "bbb"});
hashMap.insert({3, "ccc"});
hashMap.erase(2);
for (auto& pair : hashMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
输出结果为:
1: aaa
3: ccc
C++哈希表添加元素
C++ 中可以使用标准库中的 unordered_map 来实现哈希表,添加元素可以通过 insert 函数来完成。例如:
```c++
#include <unordered_map>
#include <string>
int main() {
// 创建一个 unordered_map,键为字符串,值为整数
std::unordered_map<std::string, int> myMap;
// 添加一个元素,键为 "apple",值为 3
myMap.insert(std::make_pair("apple", 3));
// 或者可以使用下面的语法
myMap["banana"] = 5;
return 0;
}
```
注意,如果要使用 `[]` 运算符来添加元素,需要保证该键在哈希表中不存在,否则会更新该键对应的值。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)