C++-STL(4)-unordered_set-自定义类型-实例源码

       自定义类型一般有三种实现方式,百度一下就出来了。目的都是重写hash<Key> 以及 equal<Key>。
 其实都是三步走:
     1.自定义对象;
     2.重载operator;
     3,哈希函数 
 本文给出两种好用的,一个是struct的,一个是class的。照着做肯定可以用起来。
 本文的struct和class 成员变量都是基本数据类型,成员变量有自定义类型的参看
1.struct

struct Rect {
    int width;
    int height;
    string name;

public:
    Rect(int a, int b,string str)
    {
        width = a;
        height = b;
        name = str;
    }

};
//哈希函数
struct Rect_hash
{   
    size_t operator()(const Rect& r1) const
    {
        return hash<string>()(r1.name) ^ hash<int>()(r1.width) ^ hash<int>()(r1.height);
    }
};
//equal相当于重载operator==
// int->string  to_string
//string temp = to_string(rc1.name) 
struct Rect_equal
{
    bool operator()(const Rect& rc1, const Rect& rc2) const noexcept
    {
        return rc1.width == rc2.width && rc1.height == rc2.height && rc1.name == rc2.name;
    }

};

void hashset_rect()
{
    unordered_set < Rect, Rect_hash, Rect_equal> rectS;
    rectS.insert({ 0,0,"rect0" });
    rectS.insert({ 1,1,"rect1" });
    rectS.insert({ 2,2,"rect2" });
    rectS.insert({ 3,3,"rect3" });
    for (auto it = rectS.begin(); it != rectS.end(); ++it)
    {
        cout << "name=" << it->name << ",width=" << it->width << ",heigh=" << it->height << endl;
    }
}

2.class
 

class Rect {
public:
    int width;
    int height;
    string name;


    Rect(int a, int b, string str)
    {
        width = a;
        height = b;
        name = str;
    }
    bool operator==(const Rect& rc) const
    {
        return name == rc.name && width == rc.width && height==rc.height;
    }

};

class Rect_hash
{
public:
    size_t operator()(const Rect& rc)const
    {
        return hash<string>()(rc.name) ^ hash<int>()(rc.width) ^ hash<int>()(rc.height);
    }

};

void hashset_rect()
{
    cout<<"*******************"<<endl;
    unordered_set < Rect, Rect_hash> rectS;
    rectS.insert(Rect(0, 0, "rect0"));
    rectS.insert(Rect(1, 1, "rect1"));
    rectS.insert(Rect(2, 2, "rect2"));
    rectS.insert(Rect(3, 3, "rect3"));

    for (auto it = rectS.begin(); it != rectS.end(); ++it)
    {
        cout << "name=" << it->name << ",width=" << it->width << ",heigh=" << it->height << endl;
    }
}

 

原文链接: https://www.cnblogs.com/jasmineTang/p/14369297.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++-STL(4)-unordered_set-自定义类型-实例源码

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/327675

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午4:22
下一篇 2023年3月1日 下午4:22

相关推荐