C++ 类内集合成员变量的自定义比较

问题描述 投票:0回答:1

如何为以下示例指定自定义比较 这个想法是访问类中的成员变量进行比较。

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:类内的结构

方法#2 函子

方法#3:使用绑定

c++ set custom-compare
1个回答
0
投票

您需要像这样重载

operator<
https://onlinegdb.com/PJXt_UmEz

#include <map>
#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::map<my_class_t,int> map{{{1,1},1}, {{1,2},2}};
    int value = map[{1,2}];
    std::cout << value;
    return value;
}
© www.soinside.com 2019 - 2024. All rights reserved.