Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

จะสร้าง unordered_map ของคลาสที่ผู้ใช้กำหนดใน 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