1

https://leetcode.com/problems/sort-array-by-increasing-frequency/

In this leetcode question, I wrote the following code:

class Solution {
public:
    bool compare(pair<int,int>p1,pair<int,int>p2)
    {
        if(p1.second<p2.second)
            return true;
        else if(p1.second==p2.second)
        {
            if(p1.first>p2.first)
                return true;
            else
                return false;
        }
        else
            return false;
    }
    vector<int> frequencySort(vector<int>& nums) {
        vector<int>final(nums.size());int k=0;map<int,int>mpp;
        for(int i=0;i<nums.size();i++)
        {
            mpp[nums[i]]++;
        }
        sort(mpp.begin(),mpp.end(),compare);
        for(auto it:mpp)
        {
            while(it.second)
            {
                final[k++]=it.first;
                it.second--;
            }
        }
        return final;
    }
};

This gives me the following error:

Line 23: Char 36: error: reference to non-static member function must be called
        sort(mpp.begin(),mpp.end(),compare);
                                   ^~~~~~~

Can someone please point out the mistake? (PS: I am new to Object Oriented Programming)

Ricky Sixx
  • 581
  • 1
  • 10
  • 25
Vatsal A Mehta
  • 392
  • 2
  • 15
  • Does this answer your question? [std::sort function with custom compare function results error: reference to non-static member function must be called](https://stackoverflow.com/questions/37767847/stdsort-function-with-custom-compare-function-results-error-reference-to-non) – Botje Oct 15 '21 at 11:11
  • I found an exact duplicate of your question in ten seconds. Please search SO before asking a question. – Botje Oct 15 '21 at 11:11
  • @Botje ,I had tried that but the issue persists. – Vatsal A Mehta Oct 15 '21 at 11:34
  • Please show us the different error you get when add the `static` keyword to `compare`, because it works for me. – Botje Oct 15 '21 at 11:37
  • @Botje,In file included from prog_joined.cpp:1: error: invalid operands to binary expression ('std::_Rb_tree_iterator>' and 'std::_Rb_tree_iterator>') /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_algo.h:4899:12: note: in instantiation of function template specialization – Vatsal A Mehta Oct 15 '21 at 12:13
  • You cannot sort an `std::map`. You need to rethink that part. – Botje Oct 15 '21 at 12:15
  • Thats why I had asked the qsn,despite a similar one being in SO.Thanks for clarifying – Vatsal A Mehta Oct 15 '21 at 12:37

2 Answers2

1

As a workaround you can dump the map's pairs into a std::vector<std::pair<int,int>> first:

std::vector<std::pair<int,int>> intermediate(mpp.begin(), mpp.end());
std::sort(begin(intermediate), end(intermediate), compare);

and then walk intermediate instead.

Botje
  • 26,269
  • 3
  • 31
  • 41
-1

In C++ Maps cannot be sorted even if you use a Custom Comparator.

Vatsal A Mehta
  • 392
  • 2
  • 15