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

前端 未结 4 1662
耶瑟儿~
耶瑟儿~ 2021-01-12 00:23

My priority queue declared as:

std::priority_queue<*MyClass> queue;

class MyClass {
    bool operator<( const MyClass* m ) const;
}
4条回答
  •  半阙折子戏
    2021-01-12 01:00

    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
    struct ptr_less
        : public binary_function {  
            bool operator()(const T& left, const T& right) const{
                return ((*left) <( *right));
            }
    };
    
    std::priority_queue, ptr_less > que; 
    

    Otherwise you can get away with the simplified version:

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

提交回复
热议问题