C++ unordered_map的用法

本文详细介绍了C++中的unordered_map容器,包括基本操作如插入、查找、访问和删除,以及如何使用自定义类型、哈希函数和Lambda表达式进行更复杂的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述

unordered_map 在 C++ 中是一个非常有用的容器,它允许你存储键值对,并且提供了基于键的快速查找。以下是一些 unordered_map 的用法举例:

  1. 基本操作
    插入元素
#include <iostream>  
#include <unordered_map>  
#include <string>  
  
int main() {  
    std::unordered_map<std::string, int> myMap;  
    myMap["apple"] = 1;  
    myMap["banana"] = 2;  
    myMap["cherry"] = 3;  
  
    // 使用 insert 函数插入  
    myMap.insert(std::pair<std::string, int>("date", 4));  
    // 或者使用 make_pair  
    myMap.insert(std::make_pair("fig", 5));  
  
    return 0;  
}

查找元素

if (myMap.find("banana") != myMap.end()) {  
    std::cout << "Found banana with value: " << myMap["banana"] << std::endl;  
} else {  
    std::cout << "Banana not found" << std::endl;  
}

访问元素

int value = myMap["apple"]; // 直接使用键访问值  
std::cout << "Value of apple: " << value << std::endl;

删除元素

myMap.erase("cherry"); // 根据键删除元素

遍历元素

for (const auto& pair : myMap) {  
    std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;  
}
  1. 使用自定义类型和哈希函数
    如果你想要使用自定义类型作为 unordered_map 的键,你需要为该类型提供一个哈希函数。以下是一个使用自定义类型和哈希函数的例子:
#include <iostream>  
#include <unordered_map>  
#include <functional> // for hash  
  
struct Person {  
    std::string name;  
    int age;  
  
    bool operator==(const Person& other) const {  
        return name == other.name && age == other.age;  
    }  
};  
  
namespace std {  
    template<>  
    struct hash<Person> {  
        size_t operator()(const Person& p) const {  
            size_t h1 = hash<string>()(p.name);  
            size_t h2 = hash<int>()(p.age);  
            return h1 ^ (h2 << 1); // 合并哈希值  
        }  
    };  
}  
  
int main() {  
    std::unordered_map<Person, std::string> people;  
    people[Person{"Alice", 30}] = "Software Engineer";  
    people[Person{"Bob", 25}] = "Data Scientist";  
  
    for (const auto& entry : people) {  
        std::cout << "Name: " << entry.first.name << ", Age: " << entry.first.age  
                  << ", Occupation: " << entry.second << std::endl;  
    }  
  
    return 0;  
}

在这个例子中,我们定义了一个 Person 结构体,并为它提供了一个哈希函数。这个哈希函数结合了 name 和 age 成员的哈希值来生成 Person 的唯一哈希值。然后,我们可以使用这个自定义类型作为 unordered_map 的键。

  1. 使用 Lambda 表达式作为查找条件
    你还可以使用 find_if 算法和 lambda 表达式来基于更复杂的条件查找元素:
#include <iostream>  
#include <unordered_map>  
#include <algorithm>  
  
int main() {  
    std::unordered_map<std::string, int> myMap;  
    myMap["apple"] = 1;  
    myMap["banana"] = 2;  
    myMap["cherry"] = 3;  
  
    // 使用 find_if 和 lambda 查找值大于 2 的元素  
    auto it = std::find_if(myMap.begin(), myMap.end(), [](const std::pair<std::string, int>& pair) {  
        return pair.second > 2;  
    });  
  
    if (it != myMap.end()) {  
        std::cout << "Found an element with value greater than 2: " << it->first << ",
### C++ 中 `std::unordered_map` 的数据结构及使用方法 #### 数据结构概述 `std::unordered_map` 是一种关联容器,内部通过哈希表(hash table)来实现。它的主要特点是能够以平均常数时间复杂度完成插入、删除和查找操作[^1]。 #### 基本头文件 要使用 `std::unordered_map`,需要包含 `<unordered_map>` 头文件。 ```cpp #include <unordered_map> ``` #### 定义与初始化 可以通过多种方式定义并初始化一个 `std::unordered_map`: ```cpp // 定义一个空的 unordered_map std::unordered_map<int, std::string> myMap; // 初始化时赋值 std::unordered_map<std::string, int> studentAges = { {"Alice", 20}, {"Bob", 22} }; ``` #### 插入元素 可以使用 `insert()` 方法或者直接通过下标运算符 `[ ]` 来插入键值对[^3]。 ```cpp myMap.insert({42, "Answer"}); // 使用 insert() 方法 myMap[7] = "Lucky"; // 使用下标运算符 ``` #### 查找元素 利用 `find()` 函数或下标访问已存在的键值对。如果尝试访问不存在的键,则会自动创建该键并将对应的值设为默认值(对于内置类型来说通常是零或其他类型的默认构造对象),这可能不是期望的行为。 ```cpp if(myMap.find(42) != myMap.end()) { std::cout << "Found: " << myMap.at(42) << '\n'; // at() 抛出异常当找不到指定 key } // 下标访问存在风险 try{ std::cout << "Value of non-existing key is: " << myMap.at(99) << '\n'; } catch(std::out_of_range& e){ std::cerr << "Error: " << e.what() << '\n'; } ``` #### 遍历所有元素 遍历时可采用范围for循环或是传统的迭代器方式进行[^2]。 ```cpp // 范围 for 循环 for(auto const &[key, value] : studentAges){ std::cout << "Key: " << key << ", Value: " << value << "\n"; } // 迭代器方式 for(auto it=studentAges.begin(); it!=studentAges.end(); ++it){ std::cout << "Student ID: " << (*it).first << "; Age: " << (*it).second << "\n"; } ``` #### 删除元素 支持单个元素删除以及清除整个容器内的所有元素。 ```cpp myMap.erase(42); // 移除特定 key 对应的 element myMap.clear(); // 清空全部 contents ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知其所以然也

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值