Word Count with map
Completed
Read a line of words and print each distinct word with its count in alphabetical order using map<string, int>.
Input
One line.
Output
One line per word.
Example
Input
to be or not to be
Output
be 2 not 1 or 1 to 2
Editor
C++
Hints
counts[w]++ creates the entry with 0 the first time.
A map keeps its keys sorted.
Solution explanation
Structured bindings make iterating key/value pairs readable.
Show solution
#include <iostream>
#include <map>
#include <sstream>
#include <string>
using namespace std;
int main() {
string line, w;
getline(cin, line);
istringstream in(line);
map<string, int> counts;
while (in >> w) counts[w]++;
for (const auto &[word, count] : counts) cout << word << " " << count << "\n";
return 0;
}