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

c++ hash

作者:暗夜骑士   发布日期:2025-06-30   浏览:12

#include <iostream>
#include <unordered_map>
#include <string>

int main() {
    // 创建一个哈希表,键为字符串,值为整数
    std::unordered_map<std::string, int> hash_table;

    // 向哈希表中插入键值对
    hash_table["apple"] = 1;
    hash_table["banana"] = 2;
    hash_table["orange"] = 3;

    // 查找键对应的值
    std::string key = "banana";
    if (hash_table.find(key) != hash_table.end()) {
        std::cout << "Value of " << key << " is " << hash_table[key] << std::endl;
    } else {
        std::cout << key << " not found in hash table" << std::endl;
    }

    // 遍历哈希表并打印所有键值对
    for (const auto& pair : hash_table) {
        std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
    }

    return 0;
}

解释说明

  1. 引入头文件

    • #include <iostream>:用于输入输出操作。
    • #include <unordered_map>:用于创建哈希表(无序映射)。
    • #include <string>:用于处理字符串。
  2. 创建哈希表

    • 使用 std::unordered_map 创建一个哈希表 hash_table,其中键是 std::string 类型,值是 int 类型。
  3. 插入键值对

    • 使用 hash_table["key"] = value; 的方式向哈希表中插入键值对。
  4. 查找键对应的值

    • 使用 hash_table.find(key) 方法查找键是否存在于哈希表中。如果存在,则返回对应的迭代器;否则返回 hash_table.end()
    • 使用 hash_table[key] 获取键对应的值。
  5. 遍历哈希表

    • 使用范围循环 for (const auto& pair : hash_table) 遍历哈希表中的每个键值对,并打印出来。

这段代码展示了如何使用 C++ 中的 std::unordered_map 实现哈希表的基本操作,包括插入、查找和遍历。

上一篇:c++泛型

下一篇:c++ 格式化字符串

大家都在看

c++闭包

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

c++ 注释

c++如何判断素数

c++freopen怎么用

c++ 获取系统时间

c++进制转换函数

c++ tcp

c++ gcd函数

c++ cli

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

Laravel 中文站