So, I have the following code:
#include <iostream>
#include <unordered_map>
#include <utility>
#include <map>
using namespace std;
struct cmp
{
bool operator() (const pair<int,int>&a, const pair<int,int>&b)
{
if (a.first == b.first)
return a.second<b.second;
else
return a.first > b.first;
}
};
int main (void)
{
int i=0,n,foo;
cin>>n;
map <int, pair<int,int>, cmp > mymap;
while (i != n)
{
//auto it = mymap.begin();
cin>>foo;
if (mymap.find(foo) == mymap.end())
{
mymap[foo].make_pair(1,i);
}
else
{
mymap[foo].first++;
}
i++;
}
auto it = mymap.begin();
while (it != mymap.end())
{
cout<<it->first<<"\t"<<it->second.first<<"\t"<<it->second.second;
cout<<"\n";
}
return 0;
}
What this code does is basically takes input elements and sorts them by frequency (in decreasing order). And if frequency of two elements are same, then it outputs that which appeared first in the input list.
For ex: I/P: 2 5 2 8 5 6 8 8
O/P: 8 8 8 2 2 5 5 6
I have doubts in two places. Firstly, in the comparator function which I wrote, it seems to be correct but it gives an error on compilation which is,
no matching function for call to object of type 'const cmp'
{return static_cast<const _Hash&>(*this)(__x);}
Also, the loop that I am using for printing the output, is that correct, especially, it->second.first
?