이 튜토리얼에서는 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