C++ STL unordered_set 與 unordered_map的基本用法完全指南
概述
在C++標(biāo)準(zhǔn)模板庫(STL)中,unordered_set和 unordered_map是基于哈希表實現(xiàn)的容器,提供了平均O(1)時間復(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存儲自定義數(shù)據(jù)類型,則需要自己設(shè)計哈希函數(shù)。
3. KeyEqual(鍵相等比較函數(shù),默認(rèn):std::equal_to<Key>)
作用:判斷兩個鍵是否相等
內(nèi)置數(shù)據(jù)類型和string類,可以使用stl內(nèi)置的鍵相等比較函數(shù),該參數(shù)可缺省,如果用unordered_set存儲自定義數(shù)據(jù)類型,則需要自己設(shè)計鍵相等比較函數(shù),該函數(shù)是實現(xiàn)鍵值去重和查找必不可少的。
4. Allocator(分配器類型,默認(rèn):std::allocator<pair<const Key, T>>)
作用:管理內(nèi)存的分配和釋放
絕大多數(shù)情況使用默認(rèn)分配器,特殊場景(如嵌入式系統(tǒng)、實時系統(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; // 元素個數(shù): 5
cout << "empty: " << uset.empty() << endl; // 是否為空: 0(false)
cout << "max_size: " << uset.max_size() << endl; // 可存儲的最大數(shù)量
2. 迭代器
unordered_set<int> uset = {10, 20, 30, 40, 50};
// 遍歷(無序,但通常按哈希桶順序)
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 - 返回元素個數(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}); // 插入多個元素
// emplace - 原地構(gòu)造
uset.emplace(50);
// erase - 刪除元素
uset.erase(20); // 通過值刪除
auto it = uset.find(30);
if(it != uset.end()) {
uset.erase(it); // 通過迭代器刪除
}
uset.erase(uset.begin(), uset.end()); // 范圍刪除
// clear - 清空所有元素
uset.clear();
注意:使用insert和emplace插入單個元素時,返回值為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實現(xiàn)哈希表示意圖,對于哈希值相同的元素,STL選擇將其用鏈表鏈接起來,掛到同一個桶上面去。

在C++ STL中,unordered_set和 unordered_map的默認(rèn)最大負(fù)載因子是 1.0
(負(fù)載因子 = 插入元素數(shù)量 / 桶數(shù)量)
這意味著當(dāng)容器中的元素數(shù)量超過桶的數(shù)量時(即負(fù)載因子 > 1.0),就會觸發(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個元素的空間 // 重新哈希 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存儲自定義數(shù)據(jù)類型,則需要自己設(shè)計哈希函數(shù)。
4. KeyEqual(鍵相等比較函數(shù),默認(rèn):std::equal_to<Key>)
作用:判斷兩個鍵是否相等
內(nèi)置數(shù)據(jù)類型和string類,可以使用stl內(nèi)置的鍵相等比較函數(shù),該參數(shù)可缺省,如果用unordered_set存儲自定義數(shù)據(jù)類型,則需要自己設(shè)計鍵相等比較函數(shù),該函數(shù)是實現(xiàn)鍵值去重和查找必不可少的。
5. Allocator(分配器類型,默認(rèn):std::allocator<pair<const Key, T>>)
作用:管理內(nèi)存的分配和釋放
絕大多數(shù)情況使用默認(rèn)分配器,特殊場景(如嵌入式系統(tǒng)、實時系統(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. 元素訪問
unordered_map<string, int> umap = {{"apple", 5}, {"banana", 3}};
// operator[] - 訪問或插入元素
umap["apple"] = 10; // 修改現(xiàn)有元素
umap["orange"] = 7; // 插入新元素
int val = umap["apple"]; // 訪問元素
// at - 訪問元素,越界時拋出異常
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 - 插入鍵值對
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); // 不會替換現(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); // 插入新鍵值對
// erase
umap.erase("banana"); // 通過鍵刪除
auto it = umap.find("orange");
if(it != umap.end()) {
umap.erase(it); // 通過迭代器刪除
}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 鍵唯一,每個鍵對應(yīng)一個值;unordered_multimap 允許鍵重復(fù),一個鍵可對應(yīng)多個值。
unordered_set 鍵唯一;unordered_multiset 允許鍵重復(fù)。
那么本期的內(nèi)容就到這里了,覺得有收獲的同學(xué)們可以給個點贊、評論、關(guān)注、收藏哦,謝謝大家。
到此這篇關(guān)于C++ STL unordered_set 與 unordered_map的基本用法完全指南的文章就介紹到這了,更多相關(guān)C++ STL unordered_set 與 unordered_map內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C語言編程之三個方法實現(xiàn)strlen函數(shù)
本篇文章是C語言編程篇,主要為大家介紹C語言編程中實現(xiàn)strlen函數(shù)的三個方法講解,有需要的朋友可以借鑒參考下,希望可以有所幫助2021-09-09
解析為何要關(guān)閉數(shù)據(jù)庫連接,可不可以不關(guān)閉的問題詳解
本篇文章是對為何要關(guān)閉數(shù)據(jù)庫連接,可不可以不關(guān)閉的問題進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
C語言數(shù)據(jù)結(jié)構(gòu)之堆排序源代碼
這篇文章主要為大家詳細(xì)介紹了C語言數(shù)據(jù)結(jié)構(gòu)之堆排序源代碼,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-01-01
Qt實現(xiàn)網(wǎng)易云音樂進(jìn)度條效果
這篇文章主要為大家詳細(xì)介紹了Qt實現(xiàn)網(wǎng)易云音樂進(jìn)度條效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-08-08
c++實現(xiàn)LinkBlockedQueue的問題
這篇文章主要介紹了c++實現(xiàn)LinkBlockedQueue的問題,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-10-10

