Sorting elements according to frequency of occurence in C++ I am sorting the elements in an array according to their frequency of occurrence in decreasing order and if two elements have same frequency then they are sorted in increasing order. I have used std::map to count the frequency and then copy the elements from std::map to std::vector&lt;std::pair&lt;K, V&gt;&gt;.

#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;map&gt;
#include &lt;algorithm&gt;

struct greater
{
   template&lt;class T&gt;
   bool operator()(T const &amp;a, T const &amp;b) const { return a.second &gt; b.second; }
};

template&lt;class T&gt;
void sortByFreq(std::vector&lt;T&gt;&amp; v)
{
  std::map&lt;T, T&gt; count;

  for (int i : v){
      count[i]++;
  }

  std::vector&lt;std::pair&lt;T, T&gt;&gt; mapcopy;

  for(auto itr = count.begin(); itr != count.end(); itr++)
  {
    mapcopy.push_back(*itr);
  }

  std::sort(mapcopy.begin(), mapcopy.end(), greater());

  std::cout &lt;&lt; "Elements sorted according to Frequency \n";

  auto itr = mapcopy.begin();
  while(itr != mapcopy.end())
  {
    for(int i = 0; i &lt; itr-&gt;second; i++)
    {
      std::cout &lt;&lt; itr-&gt;first &lt;&lt;" ";
    }
  itr++;
  }

}



int main()
{
  std::vector&lt;int&gt; vec = {2, 3, 2, 4, 5, 12, 12, 3, 4, 3};
  sortByFreq(vec);
  std::vector&lt;char&gt; c ={ 'e', 't', 'r', 'e', 't', 't', 'f'};
  sortByFreq(c);
return 0;
}


The Output is

3 3 3 2 2 4 4 12 12 5
t t t e e f r 


Review this code and help me to improve it.
Advice 1

Do not print in the algorithms. If your friend wants to reuse your implementation on large vectors, he will be overwhelmed with the plethora of output.

Advice 2

You can simplify your sorting algorithm via an appropriate comparator:

template&lt;class T&gt;
void sortByFreq2(std::vector&lt;T&gt;&amp; v)
{
    std::unordered_map&lt;T, size_t&gt; count;

    for (T i : v) {
        count[i]++;
    }

    std::sort(
        v.begin(), 
        v.end(),
        [&amp;count](T const&amp; a, T const&amp; b) {
        if (a == b) {
            return false;
        }
        if (count[a] &gt; count[b]) {
            return true;
        }
        else if (count[a] &lt; count[b]) {
            return false;
        }
        return a &lt; b;
    });
}


Note unordered_map&lt;T, size_t&gt; instead of map&lt;T, T&gt; since you don't need to keep the keys T in order (more efficient).

Hope that helps.