如何在 C++ 中建立一個使用者自定義類的無序對映?


在本教程中,我們將討論一個程式來了解如何在 C++ 中建立一個使用者自定義類的無序對映。

要建立一個來自使用者自定義類的無序對映,我們將作為第三個引數將雜湊函式傳遞為類方法。

示例

 實際演示

#include <bits/stdc++.h>
using namespace std;
//objects of class to be used as key values
struct Person {
   string first, last;
   Person(string f, string l){
      first = f;
      last = l;
   }
   bool operator==(const Person& p) const{
      return first == p.first && last == p.last;
   }
};
class MyHashFunction {
   public:
   //using sum of length as hash function
   size_t operator()(const Person& p) const{
      return p.first.length() + p.last.length();
   }
};
int main(){
   unordered_map<Person, int, MyHashFunction> um;
   Person p1("kartik", "kapoor");
   Person p2("Ram", "Singh");
   Person p3("Laxman", "Prasad");
   um[p1] = 100;
   um[p2] = 200;
   um[p3] = 100;
   for (auto e : um) {
      cout << "[" << e.first.first << ", "<< e.first.last<< "] = > " << e.second << '\n';
   }
   return 0;
}

輸出

[Laxman, Prasad] = > 100
[kartik, kapoor] = > 100
[Ram, Singh] = > 200

更新於: 2020 年 2 月 25 日

515 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.