Skip to main content

Lesson 7 of 7

Practice & Quiz - STL Containers, Iterators & Algorithms

Test your knowledge of vector internals, map vs unordered_map, iterator invalidation, STL algorithms, and string_view with a practical exercise and 5 quiz questions.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Practical Exercise - Word Frequency Counter with STL

Practical Exercise - Word Frequency Counter with STL
#include <iostream>
#include <string>
#include <string_view>
#include <sstream>
#include <unordered_map>
#include <map>
#include <vector>
#include <algorithm>
#include <numeric>

// Count word frequencies using unordered_map (O(1) per word)
std::unordered_map<std::string, int> word_freq(std::string_view text) {
    std::unordered_map<std::string, int> freq;
    std::string word;
    // Use istringstream - doesn't allocate a new string from string_view
    std::istringstream iss{std::string(text)};
    while (iss >> word) {
        // Normalise to lowercase
        std::transform(word.begin(), word.end(), word.begin(), ::tolower);
        // Remove non-alpha chars
        word.erase(std::remove_if(word.begin(), word.end(),
                   [](char c){ return !std::isalpha(c); }), word.end());
        if (!word.empty()) ++freq[word];
    }
    return freq;
}

// Top N words sorted by frequency (descending), then alphabetically
std::vector<std::pair<std::string,int>> top_n(
    const std::unordered_map<std::string,int>& freq, size_t n)
{
    std::vector<std::pair<std::string,int>> v(freq.begin(), freq.end());
    std::partial_sort(v.begin(),
                      v.begin() + std::min(n, v.size()),
                      v.end(),
                      [](const auto& a, const auto& b) {
                          return a.second != b.second
                               ? a.second > b.second   // higher freq first
                               : a.first < b.first;    // alpha on tie
                      });
    if (v.size() > n) v.resize(n);
    return v;
}

int main() {
    std::string_view text =
        "the quick brown fox jumps over the lazy dog "
        "the fox was very quick and the dog was very lazy";

    auto freq = word_freq(text);

    // Total word count via accumulate
    int total = std::accumulate(freq.begin(), freq.end(), 0,
        [](int acc, const auto& kv){ return acc + kv.second; });
    std::cout << "Unique words: " << freq.size() << " Total: " << total << "\n\n";

    std::cout << "Top 5 words:\n";
    for (const auto& [word, count] : top_n(freq, 5)) {
        std::cout << "  " << word << ": " << count << "\n";
    }
    return 0;
}

Module Quiz

Module Quiz
Question 1 of 5

A vector has `size()=10, capacity()=16`. After `push_back` that doesn't cause reallocation, which iterators are invalidated?

Tip

Tip

Practice Practice Quiz STL Containers Iterators Algorithms in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Sequence Containers, Associative Trees & Hash Tables, Iterator Invalidation & Modern C++20 Ranges

Practice Task

Note

Practice Task - (1) Write a working example of Practice Quiz STL Containers Iterators Algorithms from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Practice Quiz STL Containers Iterators Algorithms is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.

Topics in This Module

0/7 done