How to display string letters sorted by frequency in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <algorithm>
#include <cctype>

// sortByFrequency — counts how often each letter appears and returns a sorted list
std::vector<std::pair<char,int>> sortByFrequency(const std::string &s) {
    std::vector<int> freq(26, 0);

    for (char c : s) {
        if (isalpha(c)) {
            freq[tolower(c) - 'a']++;
        }
    }

    std::vector<std::pair<char,int>> result;
    for (int i = 0; i < 26; i++) {
        result.push_back({char('a' + i), freq[i]});
    }

    sort(result.begin(), result.end(),
         [](auto &a, auto &b) { return a.second > b.second; });

    return result;
}

// Build a string sorted by frequency: ddddddddddddccccccbbbbbaaaafffeehhgs
std::string buildSortedString(const std::vector<std::pair<char,int>> &sorted) {
    std::string out;
    for (auto &p : sorted) {
        out.append(p.second, p.first);   // append 'p.first' repeated p.second times
    }
    return out;
}

int main() {
    std::string text = "bbcabddddccafffadbbcdccsedddddhhgade";

    auto sorted = sortByFrequency(text);

    // Print each letter and its frequency
    for (auto &p : sorted) {
        if (p.second != 0)
            std::cout << p.first << ": " << p.second << std::endl;
    }

    // Print the reconstructed sorted string
    std::string letters_sorted_by_frequency = buildSortedString(sorted);
    std::cout << "\nSorted string: " << letters_sorted_by_frequency << std::endl;
}


/*
run:

d: 12
c: 6
b: 5
a: 4
f: 3
e: 2
h: 2
g: 1
s: 1

Sorted string: ddddddddddddccccccbbbbbaaaafffeehhgs

*/

 



answered 3 days ago by avibootz
edited 2 days ago by avibootz
...