sort chars in vector by frequency and then by alphabetical order

I have a std::vector<char> and I would like to sort it according to the frequency of each letter. When two letters have the same frequency, they should be sorted alphabetically.

My question is similar to this one that was asked 7 years ago. But none of the answers seem to work for me.

I wrote wrote this function:

template<class T>
void sortVector(std::vector<T> &v)
{
    std::unordered_map<T, size_t> count;

    for (T i : v) {
        count[i]++;
    }
    std::sort(v.begin(), v.end(), 
        [&count](T const& a, T const& b) {
            return count[a] > count[b];
        }
    );
}

The characters are sorted by frequency, but not in alphabetical order.

How can I modify this function in order to solve my problem?



Read more here: https://stackoverflow.com/questions/68472516/sort-chars-in-vector-by-frequency-and-then-by-alphabetical-order

Content Attribution

This content was originally published by Nathan Casabieille at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: