Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement sorting method for a c++ priority_queue with pointers

My priority queue declared as:

std::priority_queue<*MyClass> queue;

class MyClass {
    bool operator<( const MyClass* m ) const;
}

is not sorting the items in the queue.

What is wrong? I would not like to implement a different (Compare) class.

Answer summary:

The problem is, the pointer addresses are sorted. The only way to avoid this is a class that 'compares the pointers'.

Now implemented as:

std::priority_queue<*MyClass, vector<*MyClass>, MyClass::CompStr > queue;

class MyClass {
    struct CompStr {
        bool operator()(MyClass* m1, MyClass* m2);
    }
}
like image 969
Peter Smit Avatar asked Jun 12 '09 10:06

Peter Smit


1 Answers

Give the que the Compare functor ptr_less.

If you want the ptr_less to be compatible with the rest of the std library (binders, composers, ... ):

template<class T>
struct ptr_less
    : public binary_function<T, T, bool> {  
        bool operator()(const T& left, const T& right) const{
            return ((*left) <( *right));
        }
};

std::priority_queue<MyClass*, vector<MyClass*>, ptr_less<MyClass*> > que; 

Otherwise you can get away with the simplified version:

struct ptr_less {
    template<class T>
    bool operator()(const T& left, const T& right) const {
        return ((*left) <( *right));
    }
};

std::priority_queue<MyClass*, vector<MyClass*>, ptr_less > que; 
like image 126
TimW Avatar answered Sep 29 '22 01:09

TimW