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

c++ unorderedmap

作者:冷血杀手   发布日期:2026-06-06   浏览:12

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

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

    // 插入元素
    umap["apple"] = 1;
    umap["banana"] = 2;
    umap["orange"] = 3;

    // 查找元素
    auto it = umap.find("banana");
    if (it != umap.end()) {
        std::cout << "Found: " << it->first << " with value " << it->second << std::endl;
    } else {
        std::cout << "Not found" << std::endl;
    }

    // 遍历 unordered_map
    for (const auto& pair : umap) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }

    // 删除元素
    umap.erase("apple");

    // 检查元素是否存在
    if (umap.count("apple") == 0) {
        std::cout << "apple is not in the map" << std::endl;
    }

    return 0;
}

解释说明

  1. 包含头文件#include <unordered_map>#include <string> 是为了使用 std::unordered_mapstd::string
  2. 创建 unordered_mapstd::unordered_map<std::string, int> umap; 创建了一个无序映射(哈希表),键是 std::string 类型,值是 int 类型。
  3. 插入元素:使用 umap["key"] = value; 的方式插入键值对。
  4. 查找元素:使用 find 方法查找指定键的元素,并通过迭代器访问其值。
  5. 遍历 unordered_map:使用范围 for 循环遍历所有键值对。
  6. 删除元素:使用 erase 方法删除指定键的元素。
  7. 检查元素是否存在:使用 count 方法检查某个键是否存在于 unordered_map 中。

上一篇:c++ readqueue

下一篇:c++while

大家都在看

c++闭包

c++向上取整的代码

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

c++ 注释

c++如何判断素数

c++怎么输入字符串

c++ functional

c++框架代码

c++格式化字符串

c++ orm框架

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

Laravel 中文站