Question 5
Back to Exercise
Count how often each letter occurs in a word (case-insensitive) using std::map, and print the letters in alphabetical order with their counts.
Solution
#include <cctype>
#include <iostream>
#include <map>
#include <string>
int main() {
std::string s = "Programming";
std::map<char, int> freq;
for (unsigned char c : s)
++freq[static_cast<char>(std::tolower(c))];
for (const auto& [ch, n] : freq)
std::cout << ch << '=' << n << ' ';
std::cout << '\n';
return 0;
}
a=1 g=2 i=1 m=2 n=1 o=1 p=1 r=2
map::operator[] creates a counter at 0 the first time a key is seen. A std::map keeps keys sorted, so the output is alphabetical.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!