C++ unordered_set::hash_function() 函式



C++ 的std::unordered_set::hash_function()用於獲取已分配元素的雜湊函式物件,該物件由 unordered_set 容器使用的雜湊函式物件計算得出。

雜湊函式物件是類的例項,具有為給定元素生成唯一雜湊值的功能。它是一個一元函式,接受 key_type 物件作為引數,並根據它返回型別為 size_t 的唯一值。

語法

以下是 std::unordered_set::hash_function() 的語法。

hasher hash_function() const;

引數

此函式不接受任何引數。

返回值

此函式返回雜湊函式。

示例 1

考慮以下示例,我們將演示 std::unordered_set::hash_function() 函式的使用。

#include <iostream>
#include <string>
#include <unordered_set>

typedef std::unordered_set<std::string> stringset;

int main () {
   stringset uSet;

   stringset::hasher fn = uSet.hash_function();

   std::cout << "This contains: " << fn ("This") << std::endl;
   std::cout << "That contains: " << fn ("That") << std::endl;

   return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出:

This contains: 16508604031426688195
That contains: 12586652871572997328

示例 2

讓我們看看以下示例,我們將計算 unordered_set 中每個元素的雜湊值。

#include <iostream>
#include <unordered_set>
using namespace std;

int main(void) {
   unordered_set <string> uSet = {"Aman", "Vivek", "Rahul"};
   auto fun = uSet.hash_function();
   for(auto it = uSet.begin(); it!=uSet.end(); ++it){
      cout << "Hash value of "<<*it<<" "<<fun(*it) << endl;  
   }
   return 0;
}

輸出

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

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

示例 3

在以下示例中,我們將計算型別為 char 的 unordered_set 中每個元素的雜湊值。

#include <iostream>
#include <unordered_set>
using namespace std;

int main(void) {
   unordered_set <char> uSet = {'a', 'b', 'c'};
   auto fun = uSet.hash_function();
   for(auto it = uSet.begin(); it!=uSet.end(); ++it){
      cout << "Hash value of "<<*it<<" "<<fun(*it) << endl;  
   }
   return 0;
}

輸出

以上程式碼的輸出如下:

Hash value of c 99
Hash value of b 98
Hash value of a 97
廣告