用于多集的自定义比较器,其中包含指向对象的指针 [英] Custom comparator for multiset that contains pointers to objects
问题描述
抱歉,标题不清楚,实际上我想不出一个标题来简要描述我的问题.
Sorry for the unclear title, actually I couldn't think of a title that describes my problem concisely.
但是这个问题很容易说明.我有一个Node类.我想通过其id_字段维护其对象之间的顺序.我知道制作一个多集< Node>如果我超载<,将正确维护容器中的订单. Node类中的运算符,或提供多集中的Comparator对象.但是我想声明一个多集< Node *>.容器并希望实现相同的行为.
But the question is simple to state. I have a Node class. I want to maintain order among its objects by its id_ field. I know that making a multiset<Node> will correctly maintain the order in the container if I overload < operator in Node class or provide a Comparator object in multiset. But I want to declare a multiset<Node*> container and want to achieve the same behaviour.
这是我的Node类定义:
Here is my Node class definition:
class Node {
int id_;
...
public:
Node() {
...
}
int getId() {
return id_;
}
void setId(int id) {
id_ = id;
}
...
bool operator<(const Node &input) {
return (this->id_ < input.id_);
}
};
我该怎么办?
推荐答案
我认为您的意思是,您需要的是:
I think what you mean and what you need is this:
template <typename T, typename Pred = std::less<T>>
struct ptr_compare : Pred
{
ptr_compare(Pred const & p = Pred()) : Pred(p) { }
bool operator()(T const * p1, T const * p2) const
{
return Pred::operator()(*p1, *p2);
}
};
typedef std::multiset<Node*, ptr_compare<Node>> node_ptr_set;
对于需要二进制谓词且要间接应用谓词的任何容器,都可以使用ptr_compare
模板.
You can use the ptr_compare
template for any container that requires a binary predicate and you want to apply the predicate indirectly.
这篇关于用于多集的自定义比较器,其中包含指向对象的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!