如何在C++中创建一个用户定义类或结构的unordered_set

如何在C++中创建一个用户定义类或结构的unordered_set

unordered_set 内部实现哈希表来存储元素。默认情况下,我们只能存储预定义类型,如int,string,float等。
如果我们想存储用户定义类型作为结构体的元素,则编译器将显示错误,因为在将元素存储到unordered_set之前,编译器会执行一些检查。而当比较两个用户定义类型时,编译器无法比较它们,因此会生成错误。

因此,为了在unordered_set中存储结构体,需要设计一些比较函数。由于unordered_set还存储实现哈希表以存储元素,因此我们还必须实现散列函数以执行散列相关工作。

以下方法解释了其实现。

实现: 我们创建一个结构体类型并在其中定义一个比较函数,该函数将用于比较两个结构体类型对象。由于unordered_set在内部实现哈希函数,因此我们还应该为用户定义的类型对象实现哈希函数。

语法 为了存储用户定义类型元素,unordered_set应遵循以下语法

unordered_set(elementType, MyHashType) us;
// element type是用户定义的类型,MyHashType是实现哈希函数的类

以下代码解释了它。

// CPP实现,使用
// 结构中的自定义数据类型
#include <bits/stdc++.h>
using namespace std;
 
//结构体定义
struct Test {
 
    int id;
 
    //此函数用于unordered_set比较
    // Test元素。
    bool operator==(const Test& t) const
    {
        return (this->id == t.id);
    }
};
 
//哈希函数的类
class MyHashFunction {
public:
    //id作为返回值的哈希函数
    size_t operator()(const Test& t) const
    {
        return t.id;
    }
};
 
// Driver方法
int main()
{
    //在以下每个结构中放置值
    Test t1 = {110},t2 = {102},
         t3 = {101},t4 = {115};
 
    //定义具有结构作为元素的unordered_set。
    unordered_set<Test,MyHashFunction> us;
 
    //将结构插入unordered_set
    us.insert(t1);
    us.insert(t2);
    us.insert(t3);
    us.insert(t4);
 
    //打印unordered_set的元素
    for (auto e:us) {
        cout<< e.id<<“”;
    }
 
    返回0;
} ```  

**输出:** ```cpp 115 101 110 102

输出:

115 101 110 102

以下是另一个示例,其中我们使用预定义的哈希函数来创建定义类的总哈希函数。

// 用于演示unordered_set的自定义数据类型的CPP程序
# include <bits/stdc++.h>
using namespace std;
 
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:
 
    // 我们使用字符串的预定义哈希函数
    // 并将我们的哈希函数定义为哈希值的XOR。
    size_t operator()(const Person& p) const
    {
        return (hash<string>()(p.first)) ^ (hash<string>()(p.last));
    }
};
 
// 主函数
int main()
{
    unordered_set<Person, MyHashFunction> us;
    Person p1("kartik", "kapoor");
    Person p2("Ram", "Singh");
    Person p3("Laxman", "Prasad");
 
    us.insert(p1);
    us.insert(p2);
    us.insert(p3);
 
    for (auto e : us) {
        cout << "[" << e.first << ", "
             << e.last << "]\n";
    }
 
    return 0;
}  

输出:

[Laxman, Prasad]
[kartik, kapoor]
[Ram, Singh]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程