Question 11 quiz

The answer should be 10 2…we will first sort on basis of pair.second (smaller comes first) and if pair.second are equal…we sort on basis of pair.first

1 Like

please also provide the question
ques 11 is

stl set iterator returned by insert

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

#include <bits/stdc++.h>
using namespace std;
int main()
{
    set<int>s;
    pair<set<int>::iterator, bool> ret;
    s.insert(1);
    s.insert(5);
    s.insert(10);
    s.insert(3);
    ret = s.insert(10);
    cout<<ret.second<<endl;
    return 0;
}

Q11. 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;
}

1 10

7 15

5 15

10 2

ans is 5 15

first thing is this is not sorting
it is a compare function which will be used while building priority queue
it’s logic is reverse of sort function because in sort function we swap a element to put it ahead
but here we swap elements in heapify function
we swap element with it’s parent when we there is misarrangement
so it is just reverse of sort function logic

i hope this helps
if yes hit a like and don’t forgot to mark doubt as resolved
if you have more doubts regarding this feel free to ask

1 Like

Thank you got it…Can you also tell about that set insert question which you posted? The insert function returns an iterator pointing to the elemnt which was inserted. But ret is of type pair…i can say " ret = s.insert(10);"…assigned ret.first…but what about ret.second? How do we know that?

by default it is 0
as it is a bool value

the function declare above show the set always contain a pair where first element is iterator and second is bool if we insert the element that is already there then ret.second returns false because set always contain unique element if we had to find ret.first then it point to previously existing value .
Eg… here we are inserting 10 which is already there so it will return false which means 0
for more reference you can learn from
http://www.cplusplus.com/reference/set/set/insert/