在C++中使用std::unordered_map存儲自定義類型需提供哈希函數(shù),1. 可特化std::hash模板并重載operator==;2. 或傳遞自定義哈希函數(shù)對象;3. 多字段組合推薦用質(zhì)數(shù)混合避免沖突;4. 注意哈希一致性與相等比較的實(shí)現(xiàn)。
在C++中使用std::unordered_map
存儲自定義類型時(shí),如果該類型沒有默認(rèn)的哈希支持,就需要手動提供一個哈希函數(shù)??梢酝ㄟ^特化std::hash
或傳遞自定義哈希函數(shù)對象來實(shí)現(xiàn)。
這是最常見的方式,適用于作為鍵的自定義結(jié)構(gòu)體或類。
示例:定義一個表示二維點(diǎn)的結(jié)構(gòu)體,并為其特化std::hash
:
#include <unordered_map><br>#include <iostream><br><br>struct Point {<br> int x, y;<br> Point(int x, int y) : x(x), y(y) {}<br><br> // 重載 == 運(yùn)算符(unordered_map 需要)<br> bool operator==(const Point& other) const {<br> return x == other.x && y == other.y;<br> }<br>};<br><br>// 自定義 hash 特化<br>namespace std {<br> template<><br> struct hash<Point> {<br> size_t operator()(const Point& p) const {<br> // 使用哈希組合技巧<br> size_t h1 = hash<int>{}(p.x);<br> size_t h2 = hash<int>{}(p.y);<br> // 簡單異或 + 位移避免對稱性問題<br> return h1 ^ (h2 << 1);<br> }<br> };<br>}<br><br>int main() {<br> unordered_map<Point, string> pointMap;<br> pointMap[Point(1, 2)] = "origin";<br> pointMap[Point(3, 4)] = "target";<br><br> for (const auto& [pt, label] : pointMap) {<br> cout << "(" << pt.x << "," << pt.y << "): " << label << endl;<br> }<br> return 0;<br>}
如果不希望或不能在std::
命名空間中添加特化(比如涉及第三方類型),可以傳入自定義哈希類作為模板參數(shù)。
struct PointHash {<br> size_t operator()(const Point& p) const {<br> size_t h1 = hash<int>{}(p.x);<br> size_t h2 = hash<int>{}(p.y);<br> return h1 ^ (h2 << 1);<br> }<br>};<br><br>// 使用方式:<br>unordered_map<Point, string, PointHash> pointMap;<br>
多個字段組合時(shí),簡單異或可能造成沖突(如(1,2)
和(2,1)
哈希相同)。推薦使用更穩(wěn)健的方法:
立即學(xué)習(xí)“C++免費(fèi)學(xué)習(xí)筆記(深入)”;
h1 + 0x9e3779b9 + (h2 << 6) + (h2 >> 2)
std::hash_combine
(雖然標(biāo)準(zhǔn)未直接提供,但可模仿 Boost 實(shí)現(xiàn))
size_t operator()(const Point& p) const {<br> size_t seed = 0;<br> seed ^= hash<int>{}(p.x) + 0x9e3779b9 + (seed << 6) + (seed >> 2);<br> seed ^= hash<int>{}(p.y) + 0x9e3779b9 + (seed << 6) + (seed >> 2);<br> return seed;<br>}
operator==
,因?yàn)?code>unordered_map需要判斷鍵是否相等std::hash
應(yīng)在std::hash
1命名空間內(nèi),且只能針對用戶定義類型unordered_map
。以上就是c++++中如何定義一個哈希函數(shù)用于自定義類型的unordered_map_c++自定義哈希函數(shù)編寫方法的詳細(xì)內(nèi)容,更多請關(guān)注php中文網(wǎng)其它相關(guān)文章!
c++怎么學(xué)習(xí)?c++怎么入門?c++在哪學(xué)?c++怎么學(xué)才快?不用擔(dān)心,這里為大家提供了c++速學(xué)教程(入門到精通),有需要的小伙伴保存下載就能學(xué)習(xí)啦!
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號