C++ unordered_map::hash_function() 函式



C++ 的std::unordered_map::hash_function() 函式用於計算 unordered_map 容器使用的雜湊函式物件。雜湊函式物件是類的例項,具有為給定元素生成唯一雜湊值的功能。

雜湊函式是一個一元函式,它接受型別為 key_type 的物件作為引數,並根據它返回型別為 size_t 的唯一值。

語法

以下是 std::unordered_map::hash_function() 函式的語法。

hasher hash_function() const;

引數

此函式不接受任何引數。

返回值

此函式返回指定引數的唯一識別符號或雜湊值。

示例 1

在以下示例中,我們演示了 hash_function() 的用法。

#include <iostream>
#include <unordered_map>
using namespace std;
int main(void) {
   unordered_map <string, string> um;
   auto fun = um.hash_function();
   cout << "Hash function for a = " << fun("a") << endl;
   cout << "Hash function for A = " << fun("A") << endl;
   return 0;
}

輸出

讓我們編譯並執行以上程式,這將產生以下結果:

Hash function for a = 4993892634952068459
Hash function for A = 6919333181322027406

示例 2

考慮以下示例,我們將使用 hash_function() 獲取指定字串值的雜湊值。

#include <iostream>
#include <unordered_map>
using namespace std;
int main(void) {
   unordered_map <string, int> um;
   auto fun = um.hash_function();
   cout << "Hash value of tutorialspoint = " << fun("tutorialspoint") << endl;
   cout << "Hash value of hyderabad = " << fun("hyderabad") << endl;
   return 0;
}

輸出

以下是上述程式碼的輸出:

Hash value of tutorialspoint = 1837101086513568625
Hash value of hyderabad = 13759299188341863370

示例 3

讓我們看一下以下示例,我們將建立一個 unordered_map 並計算每個鍵的雜湊值。

#include <iostream>
#include <unordered_map>
using namespace std;
int main(void) {
   unordered_map <string, int> um = {{"Aman", 1}, {"Vivek", 2}, {"Rahul", 3}};
   auto fun = um.hash_function();
   for(auto it = um.begin(); it!=um.end(); ++it){
      cout << "Hash value of "<<it->first<<" "<<fun(it->first) << endl;  
   }
   return 0;
}

輸出

上述程式碼的輸出如下:

Hash value of Rahul 3776999528719996023
Hash value of Vivek 13786444838311805924
Hash value of Aman 17071648282880668303
廣告