一组带有自定义比较器的指针

set of pointers with custom comparator

struct classcomp ;      

typedef struct basic{
  int a ;
  set<base*,classcomp> b ;
  int c ;
} base ;

classcomp{
  bool operator() (const base& *lhs, const base& *rhs) const{
    return (*lhs).a < (*rhs).a;}
};

我想用比较器函数 classcomp 创建一组数据类型 base 的指针。我的代码去哪儿了wrong.Someone 请帮忙

这样定义

struct classcomp {
    bool operator() (const base& *lhs, const base& *rhs) const {
        return (*lhs).a < (*rhs).a;
    }
};

struct base {
    int a;
    set<base *, classcomp> b;
    int c;
};

classcomp {...}; 应为 struct classcomp{...}; 并添加前向声明 struct baseclass base.

如果您打算这样做,也可以将 std::set 的第一个模板参数更改为 basic

还有classcomp这个类型你用的时候不完整。确保 struct classcomp 定义在 class basic 之前可用。


Offtopic 但你可以更好地重写你的 classcomp 不那么神秘:

struct classcomp {
    bool operator() (const base *lhs, const base *rhs) const {
        return lhs->a < rhs->a;
    }
};

从我在您的代码中看到的所有内容来看,您在多个地方尝试使用尚不存在的 dependent 声明。解决各种问题,一种方法是:

struct base; //forward decl announces this will exist (sooner or later)

struct classcomp
{
    // uses forward decl from before in arguments. since we're
    //  using pointers, no other type info is required. we don't
    //  actually implement this yet (we can't, we don't know what
    //  "base" really is yet).
    bool operator ()(const base* lhs, const base* rhs) const;
};

// now we define "base". when the set is declared we provide it a
//  custom comparator type that has yet to be fully fleshed out, but
//  that's ok. we know what it *will* look like (it provides the
//  proper operator() overload).
struct base
{
    int a;
    std::set<base*, classcomp> b ;
    int c;
};

// now we know what a "base" looks like. we can use that to
//  implement the comparator operator () and finish what we 
//  started from before.
inline bool classcomp::operator()(const base* lhs, const base* rhs) const
{
    return lhs->a < rhs->a;
}

从那里,您可以按原样使用 base 或从中派生,并将其中任何一个的指针推入给定 baseb 集合(我不会不要这样做,因为我会使用智能指针强加所有这些,但这是与这个问题不同的另一个问题。


嵌套比较器

如果您首先将比较器嵌套在 base 中,这会变得相当简单,您可能需要考虑这一点。这样做可以将您需要的一切都集中在一个地方:

struct base
{
    struct cmp_ptr
    {
        bool operator()(const base* lhs, const base* rhs) const
        {
            return lhs->a < rhs->a;
        }
    };

    int a;
    std::set<base*, cmp_ptr> b ;
    int c;    
};

就我个人而言,我更喜欢后者。如果您需要在其他地方使用比较器类型,可以使用 base::cmp_ptr 获取它,这在其意图上(至少对我而言)更加清晰。

希望对您有所帮助。