C++ Priority Queue with user defined comparator.
Source Code:
/* Program: Priority Queue Author: Alpha Master Date: 15 Nov 2021 */ //Header File #include<iostream> #include<queue> typedef std::pair<std::string, int> pi; int main() { std::cout<<"Priority Queue"<<std::endl; //pair pi p1 = std::make_pair("ram", 4); pi p2 = std::make_pair("shyam", 3); pi p3 = std::make_pair("abshyam", 2); pi p4 = std::make_pair("trshyam", 1); //min heap //greater auto a = [](pi a, pi b) ->bool { if(a.second > b.second){ return true;} else {return false;}}; //priority queue std::priority_queue<pi, std::vector<pi>, decltype(a) > q(a); q.push(p1); q.push(p2); q.push(p3); q.push(p4); //display while(!(q.empty())) { std::cout<<q.top().second<<std::endl; q.pop(); } return 0; }
Output:
Priority Queue 1 2 3 4