带有自定义比较器的指针集

set of pointers with custom comparator

本文关键字:指针 比较器 自定义      更新时间:2023-10-16
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 .哪里我的代码出错了。谁来帮帮我

从我在你的代码中看到的,你有几个地方,你试图使用依赖的声明,还不存在。解决各种问题的一种方法是:

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获得它,它的意图更清晰(至少对我来说)。

希望能有所帮助。

classcomp {...};应该是struct classcomp{...};,并增加struct baseclass base的前向声明。

或者将std::set的第一个模板参数更改为basic,如果您打算这样做的话。

也类型classcomp是不完整的,当你使用它。确保struct classcomp定义在类basic之前可用。


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

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

这样定义

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