Search code examples
c++priority-queue

priority_queue of vectors in increasing order


I'm trying to build a priority_queue of vectors in increasing order of the first element in each vector, in C++. Could someone help me with this? I can use a normal priority_queue with all vector elements in negative sign but is there some other way to do that? Thanks already :)


Solution

  • You can pass it a different comparator. The default is std::less, but here you'll want std::greater, for example:

    #include <functional>
    
    typedef std::vector<int> ItemType;
    
    std::priority_queue<
      ItemType,                                      // Type of items
      std::priority_queue<ItemType>::container_type, // Type of container
      std::greater<ItemType>                         // Comparison functor
      >
      my_queue;
    

    Notice the trick in the second template argument to avoid copying the default value.