C++ change priority queue to alphabetical order?

Advertisements

I am trying to create a priority queue of pairs, with book names (strings) and lengths (int).
I’d like the priority queue to have the earliest title at the top.

By default the priority queue is reverse alphabetical, returning me

(This Book, 100)
(A Book, 200)

when I’d like them to be the other way around.

I understand in the case of ints etc. I would use the specifier std::greater<int>, but what should I use in this case please? Thank you!

#include <iostream>
#include <queue>
#include <utility>
#include <string>
using namespace std;

int main(void){
    pair <string, int> tPair;
    priority_queue <pair <string, int>> pq;
    
    pq.emplace("A Book", 200);
    pq.emplace("This Book", 100);
    
    while(pq.size() != 0){
        tPair = pq.top();
        cout << "(" << tPair.first << ", " << tPair.second << ")\n";
        pq.pop();       
    }
    
    return 0;
}

>Solution :

std::pair has operator > that compares first member and then second member, so you can simply pass std::greater as comparator to your queue (note that you need to pass also Container as template argument, because Comparator is last template argument):

using QueueType = std::pair<std::string, int>;
priority_queue <QueueType, std::vector<QueueType>, std::greater<>> pq;

See it online

Leave a ReplyCancel reply