#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
// 创建一个哈希表,键为字符串,值为整数
unordered_map<string, int> hashTable;
// 插入元素到哈希表中
hashTable["apple"] = 1;
hashTable["banana"] = 2;
hashTable["orange"] = 3;
// 查找元素
string key = "banana";
if (hashTable.find(key) != hashTable.end()) {
cout << "Found " << key << ": " << hashTable[key] << endl;
} else {
cout << key << " not found" << endl;
}
// 遍历哈希表
for (auto it = hashTable.begin(); it != hashTable.end(); ++it) {
cout << "Key: " << it->first << ", Value: " << it->second << endl;
}
// 删除元素
hashTable.erase("apple");
// 检查元素是否被删除
if (hashTable.find("apple") == hashTable.end()) {
cout << "apple has been removed" << endl;
}
return 0;
}
#include <unordered_map> 引入了 C++ 标准库中的哈希表实现 unordered_map。unordered_map<string, int> 创建了一个键为字符串、值为整数的哈希表。hashTable["key"] = value; 的方式向哈希表中插入键值对。find 方法查找指定键是否存在,并输出其对应的值。for 循环和迭代器遍历哈希表中的所有键值对。erase 方法删除指定键的元素,并检查该元素是否已被成功删除。希望这段代码和解释对你理解 C++ 哈希表有所帮助。
上一篇:c++ vector 删除
下一篇:c++printf
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站