How to define a `std::set` sorting on another clas

2019-07-18 13:30发布

问题:

The code I tried, but doesn't work:

class A {
public:
    struct cmpr_t {
        bool operator() (int k1, int k2) {
            return mp[k1] < mp[k2];  // doesn't compile
        }
    };

    map<int, int> mp;  // storing key->value
    set<int, cmpr_t> ss;  // just keys, ordered by corresponding value in mp
};

I just want a map and also a set, the map stores data (key, value), and the set only contains the keys, and I want the set ordered by keys' corresponding values.

So how to define the set?

UPDATE

Compiler error:

In member function ‘bool SSet::cmpr_t::operator()(int, int)’:
error: invalid use of non-static data member ‘SSet::mp’
     unordered_map<int, int> mp;  // k -> v
                             ^
error: from this location
             return mp[l] < mp[r];
                    ^
error: invalid use of non-static data member ‘SSet::mp’
     unordered_map<int, int> mp;  // k -> v
                             ^
error: from this location
             return mp[l] < mp[r];
                            ^

回答1:

class A 
{
    struct cmpr_t
    {
        A* a;
        explicit cmpr_t(A* a) : a(a) {}
        //                      ~~~^
        bool operator()(int k1, int k2) const
        {
            return a->mp[k1] < a->mp[k2];
            //     ~~^         ~~^
        }
    };
    std::map<int, int> mp;
    std::set<int, cmpr_t> ss;

public:         
    A() : ss(cmpr_t(this)) {}
    //       ~~~~~~~~~~~^ 
};