【问题标题】:How to define a `std::set` sorting on another class data member?如何定义对另一个类数据成员的“std::set”排序?
【发布时间】:2014-12-14 09:30:39
【问题描述】:

我试过的代码,但不起作用:

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
};

我只想要一个map 和一个setmap 存储数据(键、值),而set 只包含键,我想要按键排序的set对应的值。

那么如何定义集合呢?

更新

编译器错误:

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];
                            ^

【问题讨论】:

  • cmpr_t 无法访问 A 类的私有成员。
  • @πάνταῥεῖ,我不认为这是问题所在,编译器说cmpr_t 无法访问mp,因为它不是静态数据成员。
  • 嵌套结构与它的包含类无关,您不能访问包含类的私有成员。为了使您的问题有效,请照常在您的问题中逐字发布编译器错误。
  • @πάνταῥεῖ,贴错了,我已经做了数据成员public,还是不能编译。

标签: c++ set comparator


【解决方案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)) {}
    //       ~~~~~~~~~~~^ 
};                  

【讨论】:

  • 也许将const 添加到A* a aka const A * a 会更好
  • @borisbn:只有在不想修改地图的情况下,不能使用[]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-13
  • 1970-01-01
  • 2014-05-23
  • 2022-01-10
相关资源
最近更新 更多