自定义比较器的指针集

时间:2015-07-22 12:02:45

标签: c++ pointers set

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创建一组数据类型的指针。我的代码出错了。有人请帮忙

3 个答案:

答案 0 :(得分:2)

从我在您的代码中看到的所有内容中,您可以尝试使用尚未存在的依赖声明的几个地方。解决各种问题,一种方法是:

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或从中派生,并将其中的指针推送到给定b的{​​{1}}集合中(我不会这样做)。是的,因为我会使用智能指针强制所有这些,但这是另一个与此问题分开的问题。)

嵌套比较器

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

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; }; 获取它,这在其意图中更清楚(至少对我而言)。

希望它有所帮助。

答案 1 :(得分:1)

classcomp {...};应为struct classcomp{...};,并添加struct baseclass base的前瞻声明。

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

使用它时,classcomp类型也不完整。在课堂基础之前确保struct classcomp定义可用。

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

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

答案 2 :(得分:0)

以这种方式定义

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