To use a custom class type as key in unordered_map, we need to overload the == operator and define custom hash function for this type. See the below example.
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
class Student{
public:
Student(const string& name, int age):name(name), age(age){}
friend bool operator==(const Student& lhs, const Student& rhs){
return lhs.name == rhs.name && lhs.age == rhs.age;
}
void output() const{
cout<<"Name "<<name<<" Age "<<age<<endl;
}
public:
string name;
int age;
};
struct hashStudent{
std::size_t operator()(const Student& stu) const{
return hash<string>()(stu.name)| (hash<int>()(stu.age)<<1);
}
};
int main(){
unordered_map<Student, int, hashStudent> m;
m.emplace(Student{"John", 21}, 4);
m.emplace(Student{"John", 12}, 3);
m.emplace(Student{"Ann", 24}, 2);
for(const auto& [key, val]: m){
cout<<key.name<<" "<<key.age<<" "<<val<<endl;
}
return 0;
}
No comments:
Post a Comment