Search code examples
c++priority-queue

priority queue of unique_ptr comparator


i have a priority queue that stores shared_ptr<obj>. in these obj's there is a method that returns a certain value e.g obj.method1() would return an int. I want to order the queue in ascending order of this value. I tried writing a compare class in the same file but when i add it in as the 3rd parameter it says use of undeclared identifier(I don't have access to the main function that actually runs the code) I also tried using std::greater<shared_ptr<Searchable>> as the 3rd parameter, but I'm not sure if that was the write solution. any help would be appreciated.

priority_queue<shared_ptr<obj>, vector<shared_ptr<obj>>, std::greater<shared_ptr<obj>> > Q;

That is what i have right now but i dont think its working like i wanted it to


Solution

  • Does this work for you?

    #include <memory>
    #include <queue>
    #include <vector>
    
    class obj {
    public:
        int method1() const { return 123; }
    };
    
    using obj_ptr = std::shared_ptr<obj>;
    
    class obj_ptr_comparator {
        int operator()(const obj_ptr& lhs, const obj_ptr& rhs) 
        {
            return lhs.get()->method1() < rhs.get()->method1();
        }    
    };
    
    std::priority_queue<obj_ptr, std::vector<obj_ptr>, obj_ptr_comparator> my_queue;
    

    To clarify: The item you'll get with a my_queue.pop() will be the one with the highest value of method1() (because we're essentially running std::less, the default comparator, on the method1() value instead of the shared pointer). See also the cppreference.com entry on std::priority_queue.