如何在 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
广告
数据结构
联网
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP