Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ change priority queue to alphabetical order?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading