stl priority_queue of C++ with struct

后端 未结 3 910
野性不改
野性不改 2020-12-29 14:33

How can we use STL priority_queue for struct ? Any illustration of pushing & popping , where struct has multiple data-types?
Say :

3条回答
  •  失恋的感觉
    2020-12-29 15:00

    Here is a slightly modified answer to your original question, which you deleted for no apparent reason. The original contained enough information for you to figure this out, but here it goes: provide a less than comparison that uses the int for comparison.

    All you need to do is provide a functor that implements a less-than comparison with strict weak ordering, or a less-than operator for your class implementing the same. This struct satisfies the requirements:

    struct thing
    {
        int a;
        char b;
        bool operator<(const thing& rhs) const
        {
            return a < rhs.a;
        }
    };
    

    then

    std::priority_queue q;
    thing stuff = {42, 'x'};
    q.push(stuff);
    q.push(thing{4242, 'y'}); // C++11 only
    q.emplace(424242, 'z'); // C++11 only    
    thing otherStuff = q.top();
    q.pop();
    

提交回复
热议问题