c++11 标准模板(STL)(std::unordered_map)(四)

文章详细介绍了C++11及以后版本中的unordered_map容器,包括其模板参数、迭代器的begin和end方法,以及如何使用自定义哈希函数和比较函数。同时,给出了插入元素、遍历容器并修改元素值的示例代码。
定义于头文件 <unordered_map>
template<

    class Key,
    class T,
    class Hash = std::hash<Key>,
    class KeyEqual = std::equal_to<Key>,
    class Allocator = std::allocator< std::pair<const Key, T> >

> class unordered_map;
(1)(C++11 起)
namespace pmr {

    template <class Key,
              class T,
              class Hash = std::hash<Key>,
              class KeyEqual = std::equal_to<Key>>
              using unordered_map = std::unordered_map<Key, T, Hash, Pred,
                              std::pmr::polymorphic_allocator<std::pair<const Key,T>>>;

}
(2)(C++17 起)

 

迭代器

返回指向容器第一个元素的迭代器

std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::begin, 
std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::cbegin

iterator begin() noexcept;

(C++11 起)

const_iterator begin() const noexcept;

(C++11 起)

const_iterator cbegin() const noexcept;

(C++11 起)

 返回指向容器首元素的迭代器。

若容器为空,则返回的迭代器将等于 end() 。

 

参数

(无)

返回值

指向首元素的迭代器。

复杂度

常数。

返回指向容器尾端的迭代器

std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::end, 
std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::cend

iterator end() noexcept;

(C++11 起)

const_iterator end() const noexcept;

(C++11 起)

const_iterator cend() const noexcept;

(C++11 起)

 返回指向容器末元素后一元素的迭代器。

此元素表现为占位符;试图访问它导致未定义行为。

 

参数

(无)

返回值

指向后随最后元素的迭代器。

复杂度

常数。

调用示例

#include <iostream>
#include <forward_list>
#include <string>
#include <iterator>
#include <algorithm>
#include <functional>
#include <unordered_map>
#include <time.h>

using namespace std;

struct Cell
{
    int x;
    int y;

    Cell() = default;
    Cell(int a, int b): x(a), y(b) {}

    Cell &operator +=(const Cell &cell)
    {
        x += cell.x;
        y += cell.y;
        return *this;
    }

    Cell &operator +(const Cell &cell)
    {
        x += cell.x;
        y += cell.y;
        return *this;
    }

    Cell &operator *(const Cell &cell)
    {
        x *= cell.x;
        y *= cell.y;
        return *this;
    }

    Cell &operator ++()
    {
        x += 1;
        y += 1;
        return *this;
    }


    bool operator <(const Cell &cell) const
    {
        if (x == cell.x)
        {
            return y < cell.y;
        }
        else
        {
            return x < cell.x;
        }
    }

    bool operator >(const Cell &cell) const
    {
        if (x == cell.x)
        {
            return y > cell.y;
        }
        else
        {
            return x > cell.x;
        }
    }

    bool operator ==(const Cell &cell) const
    {
        return x == cell.x && y == cell.y;
    }
};

struct myCompare
{
    bool operator()(const int &a, const int &b)
    {
        return a < b;
    }
};

std::ostream &operator<<(std::ostream &os, const Cell &cell)
{
    os << "{" << cell.x << "," << cell.y << "}";
    return os;
}

std::ostream &operator<<(std::ostream &os, const std::pair<Cell, string> &pCell)
{
    os << pCell.first << "-" << pCell.second;
    return os;
}

struct CHash
{
    size_t operator()(const Cell& cell) const
    {
        size_t thash = std::hash<int>()(cell.x) | std::hash<int>()(cell.y);
//        std::cout << "CHash: " << thash << std::endl;
        return thash;
    }
};

struct CEqual
{
    bool operator()(const Cell &a, const Cell &b) const
    {
        return a.x == b.x && a.y == b.y;
    }
};

int main()
{
    std::cout << std::boolalpha;

    std::mt19937 g{std::random_device{}()};
    srand((unsigned)time(NULL));

    auto generate = []()
    {
        int n = std::rand() % 10 + 110;
        Cell cell{n, n};
        return std::pair<Cell, string>(cell, std::to_string(n));
    };


    std::unordered_map<Cell, string, CHash, CEqual> unordered_map1;
    while (unordered_map1.size() < 5)
    {
        unordered_map1.insert(generate());
    }
    std::cout << "unordered_map1:   ";
    std::copy(unordered_map1.begin(), unordered_map1.end(), std::ostream_iterator<std::pair<Cell, string>>(std::cout, " "));
    std::cout << std::endl;
    std::cout << std::endl;


    //返回指向容器首元素的迭代器。若容器为空,则返回的迭代器将等于 end() 。
    //返回指向容器末元素后一元素的迭代器。此元素表现为占位符;试图访问它导致未定义行为。
    std::cout << "unordered_map1 const_iterator:    ";
    for (std::unordered_map<Cell, string, CHash, CEqual>::const_iterator cit =
                unordered_map1.cbegin(); cit != unordered_map1.cend(); cit++)
    {
        std::cout << *cit << " ";
    }
    std::cout << std::endl;
    std::cout << std::endl;


    for (std::unordered_map<Cell, string, CHash, CEqual>::iterator it =
                unordered_map1.begin(); it != unordered_map1.end(); it++)
    {
        it->second = std::to_string(std::rand() % 10 + 110);
    }
    std::cout << "unordered_map1:   ";
    std::copy(unordered_map1.begin(), unordered_map1.end(), std::ostream_iterator<std::pair<Cell, string>>(std::cout, " "));
    std::cout << std::endl;

    return 0;
}

输出

 

`std::unordered_map` 是 C++ 标准模板库(STL)中提供的基于 **哈希表** 实现的关联容器,用于存储键值对(key-value pairs),其查找、插入和删除操作的平均时间复杂度为 **O(1)**,最坏情况为 O(n)(哈希冲突严重时)。 它与 `std::map` 的主要区别是: - `std::map` 基于红黑树实现,键有序,时间复杂度为 O(log n); - `std::unordered_map` 基于哈希表实现,键无序,平均性能更快。 --- ### ✅ 基本特性 | 特性 | 说明 | |------|------| | 头文件 | `<unordered_map>` | | 底层结构 | 哈希表(通常使用链地址法处理冲突) | | 元素顺序 | 无序(不保证插入顺序或排序) | | 键唯一性 | 键不可重复(若重复插入会覆盖) | | 性能 | 平均 O(1),最坏 O(n) | --- ### 🧱 常用成员函数 | 函数 | 功能 | |------|------| | `insert({key, value})` | 插入一个键值对 | | `operator[key]` | 访问或创建指定键的元素(若不存在则自动插入默认值) | | `find(key)` | 查找键,返回迭代器;找不到返回 `end()` | | `erase(key)` | 删除指定键 | | `count(key)` | 返回 0 或 1(是否包含该键) | | `size()` / `empty()` | 获取大小和判断是否为 | | `clear()` | 清所有元素 | --- ### 💡 示例代码 ```cpp #include <iostream> #include <unordered_map> #include <string> int main() { // 创建一个 unordered_map:键为 string,值为 int std::unordered_map<std::string, int> ht; // 插入元素 ht.insert({"apple", 100}); ht.insert(std::make_pair("banana", 200)); ht["orange"] = 300; // 使用 operator[] 插入或赋值 // 修改已有键的值 ht["apple"] = 150; // 查找并访问元素 if (ht.find("banana") != ht.end()) { std::cout << "Found banana: " << ht["banana"] << std::endl; } // 遍历输出所有元素(注意:顺序是不确定的) std::cout << "\nAll elements:\n"; for (const auto& pair : ht) { std::cout << pair.first << " -> " << pair.second << std::endl; } // 检查是否存在某个键 if (ht.count("orange")) { std::cout << "Orange is in the map.\n"; } // 删除元素 ht.erase("banana"); std::cout << "\nAfter erasing 'banana':\n"; for (const auto& pair : ht) { std::cout << pair.first << " -> " << pair.second << std::endl; } return 0; } ``` --- ### 🔍 输出示例(顺序可能不同): ``` Found banana: 200 All elements: apple -> 150 orange -> 300 banana -> 200 Orange is in the map. After erasing 'banana': apple -> 150 orange -> 300 ``` > 注意:`unordered_map` 不保证遍历顺序,因为它是基于哈希分布的。 --- ### ⚙️ 自定义类型作为键 如果想用自定义类型(如 `struct Person`)作为键,需要满足两个条件: 1. 提供 **相等比较操作符**(`operator==` 或自定义谓词); 2. 提供 **哈希函数特化**(重载 `std::hash`)。 #### 示例:使用 `Person` 作为键 ```cpp #include <iostream> #include <unordered_map> #include <string> struct Person { std::string name; int age; // 必须定义 operator== 用于比较 bool operator==(const Person& other) const { return name == other.name && age == other.age; } }; // 为 Person 类型提供哈希特化 namespace std { template <> struct hash<Person> { size_t operator()(const Person& p) const { return hash<string>()(p.name) ^ (hash<int>()(p.age) << 1); } }; } int main() { std::unordered_map<Person, std::string> personMap; Person alice{"Alice", 30}; Person bob{"Bob", 25}; personMap[alice] = "Engineer"; personMap[bob] = "Designer"; for (const auto& [person, job] : personMap) { std::cout << person.name << ", " << person.age << " -> " << job << std::endl; } return 0; } ``` --- ### 📌 注意事项 - 如果不需要修改值,推荐使用 `find()` 而不是 `operator[]`,因为后者在键不存在时会自动插入默认构造的对象。 - 可以通过 `reserve()` 和 `max_load_factor()` 优化性能: ```cpp ht.reserve(1000); // 预分配间 ht.max_load_factor(0.5); // 控制负载因子,减少冲突 ``` - 线程安全:多个线程读可以,但写操作必须加锁。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值