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.
#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
- Hello, World · The classic first C++ program.
- Vectors and sort · Read numbers into a vector, sort them and find the largest.
- Classes and objects · A class with a constructor, private data and member functions.
- Binary search · Find a value in a sorted array in O(log n) steps.
- Competitive programming template · Fast input and output with bits/stdc++.h, ready for contest problems.