STL QUIZ 1 DOUBTS

please explain how the code runs , i mean explanation of the code of STL QUIZ 1
question numbers

10,11,13,16
Please explain breifly

hi @namanitsofficial please be specific about what part of code you did not understand.

i didn’t understand the functioning of codes of these questions.

@namanitsofficial lets start one by one, in ques 10.
Start reading the code from main() and tell me what is the first line that you did not understand properly
Please ensure that you are familiar with the working of heaps and priority queue STL before attempting this question.

stl priority_queue user defined comparator

What will be the output of following C++ code?

#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pi;
struct Compare
{
    bool operator()(pi const & a, pi const & b)
    {
         if(a.second < b.second)
         {
            return true;
         }
         else if(a.second > b.second)
         {
             return false;
         }
         else
         {
             if(a.first > b.first)
             {
                 return true;
             }
             return false;
         }
    }
};
int main()
{
    priority_queue<pi , vector<pi>, Compare>q;
    q.push({1, 5});
    q.push({5, 15});
    q.push({7, 15});
    q.push({10, 2});
    q.push({1, 10});
    cout<<q.top().first<<" "<<q.top().second<<endl;
    return 0;
}
Choices
  • 1 10
  • 7 15
  • 5 15
  • 10 2

1-> priority_queue<pi , vector, Compare>q; and insertion made in it
along with the functioning of comparator.

i didn’t understand the code at all.

@namanitsofficial please read the documentation of priority queue, you will understand the syntax then.
As for the comparator, queue containts pairs of int type, so compare function is simply comparing these pairs. Take any 2 pair examples and dry run the compare function on them.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.