WeCodeAcademy

Step 3: The C++ version

C++ gives you std::map (a word-to-count table), std::istringstream (split by whitespace with >>), std::vector and std::sort with a lambda. The code that was a page in C is now about a dozen lines, and the compiler checks the types.

ExampleC++
#include <algorithm>
#include <cctype>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
using namespace std;

string normalise(const string &text) {
  string out;
  for (char c : text) {
    out += isalpha(static_cast<unsigned char>(c)) ? static_cast<char>(tolower(static_cast<unsigned char>(c))) : ' ';
  }
  return out;
}

int main() {
  string text = "The quick brown fox jumps over the lazy dog. The end!";

  map<string, int> counts;
  istringstream words(normalise(text));
  string w;
  while (words >> w) counts[w]++;

  vector<pair<string, int>> sorted(counts.begin(), counts.end());
  sort(sorted.begin(), sorted.end(), [](const auto &a, const auto &b) {
    if (a.second != b.second) return a.second > b.second;
    return a.first < b.first;
  });

  for (const auto &[word, count] : sorted) {
    cout << word << string(7 - word.size(), ' ') << count << endl;
  }
  return 0;
}
Output
the    3
brown  1
dog    1
end    1
fox    1
jumps  1
lazy   1
over   1
quick  1

Notice there are no manual size limits: the map and the vector grow as needed, and the memory is freed automatically when they go out of scope (the RAII idea). Structured bindings (const auto &[word, count]) unpack each pair.

Quick check

What replaces the hand-written lookup loop from the C version?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.