c++ 自定义比较集合访问类的成员变量,其中实际键属于[重复]

vu8f3i0k  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(80)

此问题在此处已有答案

Using custom std::set comparator(7个答案)
17天前关闭。
此帖子已于9天前编辑并提交审核,未能重新打开帖子:
原始关闭原因未解决
如何为下面的例子指定自定义比较?其思想是访问类中的成员变量进行比较。

struct MyStruct {
    unsigned p;
    unsigned t;
};

class MyClass {
public:
    void call() {
        ob["o1_10"] ={10, 1};
        mbp[ob["o1_10"].p].insert("o1_10");

        ob["o2_20_2"] ={20, 2};
        mbp[ob["o2_20"].p].insert("o2_20");

        ob["o4_4_4"] ={4, 4};
        mbp[ob["o4_4"].p].insert("o4_4");

        ob["o5_10"] ={10, 4};
        mbp[ob["o5_10"].p].insert("o5_10");
    }
    
    
private:
    map<unsigned,set<string, Compare>> mbp;
    // Question: how to define compare using struct, operator(), statice metthod or external method so that
    //           compare fetches ob[ol] and ob[0l2] and decide based on some rules
    //           so, comparions is not based on ol and o2 and it is based on some p and t in ob[o1] and ob[02]
    // Eg:
    // bool compare(const string& o1, const string& o2) const {
    //     if (ob.at(o1).p > ob.at(o2).p)   return true;
    //     if (ob.at(o1).p == ob.at(o2).p && ob.at(o1).t < ob.at(o2).t) return true;

    //     return false;
    // }
    
    map<string, MyStruct> ob;
};

int main() {
    MyClass my_class;
    my_class.call();

    return 0;
}

字符串
需要注意的是,比较键并不是类的示例,相反,我想使用键访问类的示例进行比较,如果可以实现这一点,我就可以保存一些内存。
我试过以下方法,但每种方法都给我不同的错误给予:
1.类内结构
1.函子
1.使用绑定

aiqt4smr

aiqt4smr1#

你需要像this一样重载operator<
有了这个操作符,你可以在std::setstd::map中使用你的类(作为键)。在实践中,你可能还想重载所有的比较操作符(For C++20 overload the spaceship operator instead)。

#include <map>
#include <set>
#include <iostream>

class my_class_t
{
public:
    my_class_t(int x, int y) :
        m_x{x},
        m_y{y}
    {
    }

    friend bool operator<(const my_class_t& lhs, const my_class_t& rhs);

private:
    int m_x;
    int m_y;
};

bool operator<(const my_class_t& lhs, const my_class_t& rhs)
{
    if (lhs.m_x == rhs.m_x) 
    {
        return lhs.m_y < rhs.m_y;
    }

    return lhs.m_x < rhs.m_x;
}

int main()
{
    std::set<my_class_t> set{{1,1},{2,1},{2,2}};
    std::map<my_class_t,int> map{{{1,1},1}, {{1,2},2}};
    int value = map[{1,2}];
    std::cout << value;
    return value;
}

字符串

相关问题