Prabhakar
Prabhakar

Reputation: 377

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.

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.

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

What do I do?

Upvotes: 2

Views: 2105

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 476990

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;

You can use the ptr_compare template for any container that requires a binary predicate and you want to apply the predicate indirectly.

Upvotes: 5

Related Questions