带有自定义比较器的指针集
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 .哪里我的代码出错了。谁来帮帮我
从我在你的代码中看到的,你有几个地方,你试图使用依赖的声明,还不存在。解决各种问题的一种方法是:
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
,或者从它派生,并将两者的推入给定base
的b
集合(我不会这样做,因为我将使用智能指针强制所有这些,但这是另一个问题)。
嵌套比较
如果首先将比较器嵌套在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 base
或class 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;
};
相关文章:
- std::设置自定义比较器
- C++中"std::sort"比较器的不同类型
- 为什么指针在由后增量比较器操作时行为不同?
- 通过函数指针对类内的 STL SET 使用自定义比较器
- STL映射比较器能否以某种方式获取指向映射本身的指针?
- 将STD ::指针列表与比较器的对象列表
- 为指针后面的对象创建比较器的通用方法
- 包含指向对象的指针的多集的自定义比较器
- 如何为指针的 QList 编写自定义比较器
- 我应该为地图中的两个智能指针对制作自己的比较器吗?
- deque中指针的自定义比较器
- c++指针比较器未编译
- 使用函数指针自定义std::设置比较器
- 比较器,用于对包含指向自定义类对象的指针的向量进行排序
- 如何在c++中声明带有指针类型比较器的set
- 带有指针和比较器的优先级队列
- 带有自定义比较器的指针集
- 以指向成员的指针作为比较器/"key"的 STD 算法
- 实现结构指针的自定义比较器
- 带指针的比较器