最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C++ STL unordered_set 與 unordered_map的基本用法完全指南

 更新時(shí)間:2026年01月21日 10:08:26   作者:zephyr05  
在C++標(biāo)準(zhǔn)模板庫(kù)(STL)中,unordered_set和 unordered_map是基于哈希表實(shí)現(xiàn)的容器,提供了平均O(1)時(shí)間復(fù)雜度的查找、插入和刪除操作,本文給大家介紹C++ STL unordered_set與unordered_map完全指南,感興趣的朋友跟隨小編一起看看吧

概述

在C++標(biāo)準(zhǔn)模板庫(kù)(STL)中,unordered_setunordered_map是基于哈希表實(shí)現(xiàn)的容器,提供了平均O(1)時(shí)間復(fù)雜度的查找、插入和刪除操作。與有序容器(set、map)不同,它們不維護(hù)元素的任何特定順序。

頭文件

#include <unordered_set>
#include <unordered_map>

unordered_set 用法詳解

模板參數(shù)介紹

template < class Key,                        // unordered_set::key_type/value_type
           class Hash = hash<Key>,           // unordered_set::hasher
           class Pred = equal_to<Key>,       // unordered_set::key_equal
           class Alloc = allocator<Key>      // unordered_set::allocator_type
           > class unordered_set;

1. Key(鍵類型)

作用:定義鍵的數(shù)據(jù)類型,必須是可哈希和可比較的

2. Hash(哈希函數(shù)類型,默認(rèn):std::hash<Key>)

作用:將鍵轉(zhuǎn)換為size_t類型的哈希值

內(nèi)置數(shù)據(jù)類型和string類,可以使用stl內(nèi)置的哈希函數(shù),該參數(shù)可缺省,如果用unordered_set存儲(chǔ)自定義數(shù)據(jù)類型,則需要自己設(shè)計(jì)哈希函數(shù)。

3. KeyEqual(鍵相等比較函數(shù),默認(rèn):std::equal_to<Key>)

作用:判斷兩個(gè)鍵是否相等

內(nèi)置數(shù)據(jù)類型和string類,可以使用stl內(nèi)置的鍵相等比較函數(shù),該參數(shù)可缺省,如果用unordered_set存儲(chǔ)自定義數(shù)據(jù)類型,則需要自己設(shè)計(jì)鍵相等比較函數(shù),該函數(shù)是實(shí)現(xiàn)鍵值去重和查找必不可少的。

4. Allocator(分配器類型,默認(rèn):std::allocator<pair<const Key, T>>)

作用:管理內(nèi)存的分配和釋放

絕大多數(shù)情況使用默認(rèn)分配器,特殊場(chǎng)景(如嵌入式系統(tǒng)、實(shí)時(shí)系統(tǒng))可能需要自定義分配器

初始化相關(guān)操作

unordered_set<int> s1;                 // 空set
unordered_set<int> s2 = {1, 2, 3, 4};  // 初始化列表
unordered_set<int> s3(s2.begin(), s2.end());  // 范圍構(gòu)造

成員函數(shù)介紹

1. 容量相關(guān)

unordered_set<int> uset = {1, 2, 3, 4, 5};
cout << "size: " << uset.size() << endl;      // 元素個(gè)數(shù): 5
cout << "empty: " << uset.empty() << endl;    // 是否為空: 0(false)
cout << "max_size: " << uset.max_size() << endl;  // 可存儲(chǔ)的最大數(shù)量

2. 迭代器

unordered_set<int> uset = {10, 20, 30, 40, 50};
// 遍歷(無(wú)序,但通常按哈希桶順序)
for(auto it = uset.begin(); it != uset.end(); ++it) {
    cout << *it << " ";
}
cout<<endl;
// 使用范圍for循環(huán)
for(const auto& val : uset) {
    cout << val << " ";
}

3. 查找操作

unordered_set<string> uset = {"apple", "banana", "orange"};
// find - 返回迭代器,未找到則返回end()
auto it = uset.find("banana");
if(it != uset.end()) {
    cout << "Found: " << *it << endl;
}
// count - 返回元素個(gè)數(shù)(0或1)
if(uset.count("apple") > 0) {
    cout << "apple exists" << endl;
}

4. 修改操作

unordered_set<int> uset;
// insert - 插入元素
auto result = uset.insert(10);  // 返回pair<iterator, bool>
if(result.second) {
    cout << "Insert successful" << endl;
}
uset.insert({20, 30, 40});  // 插入多個(gè)元素
// emplace - 原地構(gòu)造
uset.emplace(50);
// erase - 刪除元素
uset.erase(20);  // 通過(guò)值刪除
auto it = uset.find(30);
if(it != uset.end()) {
    uset.erase(it);  // 通過(guò)迭代器刪除
}
uset.erase(uset.begin(), uset.end());  // 范圍刪除
// clear - 清空所有元素
uset.clear();

注意:使用insert和emplace插入單個(gè)元素時(shí),返回值為pair<iterator,bool>,result.first表示插入元素位置的迭代器,result.second表示插入是否成功。

auto result = uset.insert(10);   result的數(shù)據(jù)類型是 std::pair<std::unordered_set<int>::iterator,bool>

5. 桶操作

STL實(shí)現(xiàn)哈希表示意圖,對(duì)于哈希值相同的元素,STL選擇將其用鏈表鏈接起來(lái),掛到同一個(gè)桶上面去。

在C++ STL中,unordered_setunordered_map默認(rèn)最大負(fù)載因子是 1.0

(負(fù)載因子 = 插入元素?cái)?shù)量 / 桶數(shù)量)

這意味著當(dāng)容器中的元素?cái)?shù)量超過(guò)桶的數(shù)量時(shí)(即負(fù)載因子 > 1.0),就會(huì)觸發(fā)擴(kuò)容。

unordered_set<int> uset = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cout << "bucket_count: " << uset.bucket_count() << endl;  // 桶的數(shù)量
cout << "max_bucket_count: " << uset.max_bucket_count() << endl;
cout << "load_factor: " << uset.load_factor() << endl;  // 負(fù)載因子
cout << "max_load_factor: " << uset.max_load_factor() << endl;  // 最大負(fù)載因子
// 遍歷桶
for(size_t i = 0; i < uset.bucket_count(); ++i) {
    cout << "Bucket " << i << " has " << uset.bucket_size(i) << " elements" << endl;
}
// 查找元素所在的桶
int val = 5;
cout << val << " is in bucket " << uset.bucket(val) << endl;

6. 哈希策略

unordered_set<int> uset;
// 設(shè)置最大負(fù)載因子
uset.max_load_factor(0.7f);
// 預(yù)分配桶的數(shù)量
uset.reserve(100);  // 預(yù)留至少100個(gè)元素的空間
// 重新哈希
uset.rehash(50);  // 設(shè)置桶的數(shù)量至少為50

unordered_map 用法詳解

模板參數(shù)介紹:

template < class Key,                                    // unordered_map::key_type
           class T,                                      // unordered_map::mapped_type
           class Hash = hash<Key>,                       // unordered_map::hasher
           class Pred = equal_to<Key>,                   // unordered_map::key_equal
           class Alloc = allocator< pair<const Key,T> >  // unordered_map::allocator_type
           > class unordered_map;

1. Key(鍵類型)

作用:定義鍵的數(shù)據(jù)類型,必須是可哈希和可比較的

2. T(值類型)

作用:定義與鍵關(guān)聯(lián)的值的類型

3. Hash(哈希函數(shù)類型,默認(rèn):std::hash<Key>)

作用:將鍵轉(zhuǎn)換為size_t類型的哈希值

內(nèi)置數(shù)據(jù)類型和string類,可以使用stl內(nèi)置的哈希函數(shù),該參數(shù)可缺省,如果用unordered_set存儲(chǔ)自定義數(shù)據(jù)類型,則需要自己設(shè)計(jì)哈希函數(shù)。

4. KeyEqual(鍵相等比較函數(shù),默認(rèn):std::equal_to<Key>)

作用:判斷兩個(gè)鍵是否相等

內(nèi)置數(shù)據(jù)類型和string類,可以使用stl內(nèi)置的鍵相等比較函數(shù),該參數(shù)可缺省,如果用unordered_set存儲(chǔ)自定義數(shù)據(jù)類型,則需要自己設(shè)計(jì)鍵相等比較函數(shù),該函數(shù)是實(shí)現(xiàn)鍵值去重和查找必不可少的。

5. Allocator(分配器類型,默認(rèn):std::allocator<pair<const Key, T>>)

作用:管理內(nèi)存的分配和釋放

絕大多數(shù)情況使用默認(rèn)分配器,特殊場(chǎng)景(如嵌入式系統(tǒng)、實(shí)時(shí)系統(tǒng))可能需要自定義分配器

初始化相關(guān)操作

// 定義unordered_map
unordered_map<string, int> m1;  // 空map
unordered_map<string, int> m2 = {
    {"apple", 1},
    {"banana", 2},
    {"orange", 3}
};

成員函數(shù)介紹

1. 元素訪問(wèn)

unordered_map<string, int> umap = {{"apple", 5}, {"banana", 3}};
// operator[] - 訪問(wèn)或插入元素
umap["apple"] = 10;     // 修改現(xiàn)有元素
umap["orange"] = 7;    // 插入新元素
int val = umap["apple"];  // 訪問(wèn)元素
// at - 訪問(wèn)元素,越界時(shí)拋出異常
try {
    int value = umap.at("banana");
} catch(const out_of_range& e) {
    cout << "Key not found" << endl;
}

2. 查找操作

unordered_map<string, int> umap = {{"apple", 1}, {"banana", 2}};
// find
auto it = umap.find("apple");
if(it != umap.end()) {
    cout << it->first << ": " << it->second << endl;
}
// count
if(umap.count("banana") > 0) {
    cout << "banana exists" << endl;
}
// contains (C++20)
if(umap.contains("apple")) {
    cout << "apple exists" << endl;
}

3. 修改操作

unordered_map<string, int> umap;
// insert - 插入鍵值對(duì)
auto result = umap.insert({"apple", 5});
if(result.second) {
    cout << "Insert successful" << endl;
}
umap.insert({{"banana", 3}, {"orange", 2}});
// emplace - 原地構(gòu)造
umap.emplace("grape", 4);
// emplace_hint - 帶提示的插入
auto hint = umap.begin();
umap.emplace_hint(hint, "pear", 6);
// try_emplace (C++17) - 如果鍵不存在則插入
umap.try_emplace("apple", 10);  // 不會(huì)替換現(xiàn)有的"apple"
umap.try_emplace("mango", 8);   // 插入新的"mango"
// insert_or_assign (C++17) - 插入或賦值
umap.insert_or_assign("apple", 15);  // 替換現(xiàn)有值
umap.insert_or_assign("kiwi", 9);    // 插入新鍵值對(duì)
// erase
umap.erase("banana");  // 通過(guò)鍵刪除
auto it = umap.find("orange");
if(it != umap.end()) {
    umap.erase(it);  // 通過(guò)迭代器刪除
}

4. 遍歷操作

unordered_map<string, int> umap = {
    {"apple", 3},
    {"banana", 5},
    {"orange", 2}
};
// 使用迭代器
for(auto it = umap.begin(); it != umap.end(); ++it) {
    cout << it->first << ": " << it->second << endl;
}
// 結(jié)構(gòu)化綁定 (C++17)
for(const auto& [key, value] : umap) {
    cout << key << ": " << value << endl;
}

5. 桶操作和哈希策略

unordered_map<string, int> umap = {
    {"apple", 1}, {"banana", 2}, {"orange", 3},
    {"grape", 4}, {"pear", 5}, {"kiwi", 6}
};
// 桶信息
cout << "Bucket count: " << umap.bucket_count() << endl;
cout << "Load factor: " << umap.load_factor() << endl;
cout << "Max load factor: " << umap.max_load_factor() << endl;

6. 哈希策略

// 設(shè)置哈希策略
umap.max_load_factor(0.75f);
umap.reserve(50);  // 預(yù)留空間
umap.rehash(30);   // 重新哈希

unordered_multimap和unordered_multiset

unordered_map 鍵唯一,每個(gè)鍵對(duì)應(yīng)一個(gè)值;unordered_multimap 允許鍵重復(fù),一個(gè)鍵可對(duì)應(yīng)多個(gè)值。

unordered_set 鍵唯一;unordered_multiset 允許鍵重復(fù)。

那么本期的內(nèi)容就到這里了,覺(jué)得有收獲的同學(xué)們可以給個(gè)點(diǎn)贊、評(píng)論、關(guān)注、收藏哦,謝謝大家。

到此這篇關(guān)于C++ STL unordered_set 與 unordered_map的基本用法完全指南的文章就介紹到這了,更多相關(guān)C++ STL unordered_set 與 unordered_map內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

得荣县| 大同市| 绥芬河市| 全南县| 铜鼓县| 道真| 江门市| 女性| 上高县| 舞钢市| 聂拉木县| 内黄县| 菏泽市| 饶平县| 博白县| 佛山市| 公主岭市| 玉山县| 寿宁县| 威远县| 环江| 大名县| 镇雄县| 和田市| 英山县| 金堂县| 宁波市| 德化县| 广水市| 碌曲县| 柳州市| 肇东市| 南部县| 阿图什市| 合作市| 子洲县| 萍乡市| 丹棱县| 徐汇区| 宜黄县| 沂南县|