C++ 哈希表插入删除创建
时间: 2023-12-25 11:05:48 浏览: 78
哈希表是一种常见的数据结构,可以高效地进行元素的查找、插入和删除操作。在 C++ 中,可以使用标准库中的 unordered_map 实现哈希表。
下面是 unordered_map 的常用操作:
创建:
```c++
#include <unordered_map>
std::unordered_map<KeyType, ValueType> myMap;
```
插入元素:
```c++
myMap.insert({key, value});
```
删除元素:
```c++
myMap.erase(key);
```
查找元素:
```c++
auto iter = myMap.find(key);
if(iter != myMap.end()) {
// 找到了,可以使用 iter->second 访问对应的值
} else {
// 没找到
}
```
注意,unordered_map 中的元素是无序的。如果需要按照键值排序,可以考虑使用 std::map。
相关问题
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中的哈希表是一种使用哈希函数将键映射到存储位置的数据结构。它是一种高效的查找数据结构,可以在平均情况下实现常数时间的插入、删除和查找操作。
在C中,可以使用标准库中的哈希表实现,例如使用unordered_set或unordered_map来创建哈希表。unordered_set用于存储唯一的键,而unordered_map用于存储键值对。
下面是使用C++标准库中的unordered_map实现哈希表的示例代码:
```
#include <unordered_map>
int main() {
// 创建一个哈希表
std::unordered_map<int, std::string> hashMap;
// 向哈希表中插入元素
hashMap.insert({1, "apple"});
hashMap.insert({2, "banana"});
hashMap.insert({3, "orange"});
// 访问哈希表中的元素
std::string fruit = hashMap[1]; // 输出 "apple"
// 修改哈希表中的元素
hashMap[2] = "grape";
// 遍历哈希表中的元素
for (const auto& pair : hashMap) {
int key = pair.first;
std::string value = pair.second;
// 对每个键值对执行操作
}
// 删除哈希表中的元素
hashMap.erase(3);
return 0;
}
```