Sorting elements according to frequency of occurence in C++
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.