RUN

Count words with a map in C++

Use std::map to count how often each word appears. Press Run to try it, then change the code and run it again.

main.cpp

#include <bits/stdc++.h>
using namespace std;

int main() {
    string text = "the quick brown fox jumps over the lazy dog the end";
    stringstream ss(text);
    map<string, int> count;
    string word;
    while (ss >> word) count[word]++;

    for (const auto &[w, c] : count) cout << w << ": " << c << '\n';
}
Output

Press Run to see the output.

More C++ examples

Open the full C++ online compiler →