unordered_set 放自定义类型
时间: 2023-07-03 21:06:36 浏览: 47
可以放自定义类型,但需要提供自定义类型的哈希函数和比较函数。
哈希函数需要返回一个哈希值,用于将元素映射到桶中。比较函数用于比较两个元素是否相等,以解决哈希碰撞问题。
以下是一个示例:
```c++
#include <iostream>
#include <unordered_set>
#include <string>
struct Person {
std::string name;
int age;
bool operator==(const Person& other) const {
return name == other.name && age == other.age;
}
};
struct PersonHash {
std::size_t operator()(const Person& person) const {
return std::hash<std::string>()(person.name) ^ std::hash<int>()(person.age);
}
};
int main() {
std::unordered_set<Person, PersonHash> people = {
{"Alice", 25},
{"Bob", 30},
{"Charlie", 35}
};
for (const auto& person : people) {
std::cout << person.name << " " << person.age << std::endl;
}
return 0;
}
```
在这个例子中,我们定义了一个名为 `Person` 的结构体,其中包含一个 `name` 字符串和一个 `age` 整数。我们还定义了一个 `operator==` 函数,用于比较两个 `Person` 对象是否相等。
我们还定义了一个名为 `PersonHash` 的结构体,其中包含一个调用 `std::hash` 的哈希函数,并将 `name` 和 `age` 的哈希值进行位运算异或操作。
最后,在 `std::unordered_set` 的模板参数中指定使用 `Person` 类型和 `PersonHash` 哈希函数即可。