How to define a `std::set` sorting on another class data member?

旧街凉风 提交于 2019-12-11 03:07:10

问题


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)) {}
    //       ~~~~~~~~~~~^ 
};                  


来源:https://stackoverflow.com/questions/27467980/how-to-define-a-stdset-sorting-on-another-class-data-member

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!