Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c++哈希表

作者:花折亦无情   发布日期:2026-07-16   浏览:105

#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;
}

解释说明

  1. 包含头文件#include <unordered_map> 引入了 C++ 标准库中的哈希表实现 unordered_map
  2. 创建哈希表:使用 unordered_map<string, int> 创建了一个键为字符串、值为整数的哈希表。
  3. 插入元素:通过 hashTable["key"] = value; 的方式向哈希表中插入键值对。
  4. 查找元素:使用 find 方法查找指定键是否存在,并输出其对应的值。
  5. 遍历哈希表:使用 for 循环和迭代器遍历哈希表中的所有键值对。
  6. 删除元素:使用 erase 方法删除指定键的元素,并检查该元素是否已被成功删除。

希望这段代码和解释对你理解 C++ 哈希表有所帮助。

上一篇:c++ vector 删除

下一篇:c++printf

大家都在看

c++闭包

c++向上取整的代码

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++怎么输入字符串

c++字符串切片

c++ functional

嵌入式c++

c++框架代码

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站