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

前端 未结 4 1628
耶瑟儿~
耶瑟儿~ 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 00:57

    Not sure about the priority queue stuff because I've never used it but to do a straight sort, you can do this:

    class A
    {
        friend struct ComparePtrToA;
    public:
        A( int v=0 ):a(v){}
    private:
        int a;
    };
    
    struct ComparePtrToA
    {
        bool operator()(A* a1, A* a2) {return a1->a < a2->a;}
    };
    
    #include 
    #include 
    int _tmain(int argc, _TCHAR* argv[])
    {
        vector someAs;
        someAs.push_back(new A(1));
        someAs.push_back(new A(3));
        someAs.push_back(new A(2));
        sort( someAs.begin(), someAs.end(), ComparePtrToA() );
    }
    

    Note the memory leaks, this is only an example...

    Further note: This is not intended to be an implementation of priority queue! The vector is simply an example of using the functor I created to compare two objects via their pointers. Although I'm aware of what a priority queue is and roughly how it works, I have never used the STL features that implement them.

    Update: I think TimW makes some valid points. I don't know why he was downvoted so much. I think my answer can be improved as follows:

    class A
    {
    public:
        A( int v=0 ):a(v){}
        bool operator<( const A& rhs ) { return a < rhs.a; }
    private:
        int a;
    };
    
    struct ComparePtrToA
    {
        bool operator()(A* a1, A* a2) {return *a1 < *a2;}
    };
    

    which is cleaner (especially if you consider having a container of values rather than pointers - no further work would be necessary).

提交回复
热议问题