IntermediateLesson 12 of 206 min read

Containers and Algorithms: map, set and the Algorithm Library

Learn std::map, unordered_map and set, the erase-remove idiom, transform, partition and sort with a comparator, and count weather words with results verified against Python.

In this lesson you will

  • Use map, unordered_map and set
  • Count items with a map
  • Sort and filter with algorithms
  • Use erase-remove and partition

About 28 minutes

Which weather is most common?

Elena logs one word per observation, such as rain, sun or fog, and wants to know how often each occurs, which kinds happened at all, and the kinds sorted by frequency. The standard library has a container and an algorithm for each of these questions, and using them is shorter and less error-prone than writing loops by hand.

Container Holds Order Lookup cost
std::map Key to value pairs Sorted by key Logarithmic
std::unordered_map Key to value pairs No order Constant on average
std::set Distinct values Sorted Logarithmic
std::vector A sequence Insertion order Index: constant

The algorithms in work on pairs of iterators, and C++20 ranges let you pass the container directly. The erase-remove idiom removes elements from a vector: std::remove_if moves the elements to keep to the front and returns the new end, and the vector’s erase then cuts off the tail. In C++20, std::erase_if does both in one call. std::partition rearranges a range so that the elements satisfying a test come first. A map’s operator[] inserts a default value for a missing key, which makes counting a one-liner, ++counts[word], though it also means that merely reading a missing key with [] adds it.

#include <algorithm>
#include <iostream>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>

int main() {
    std::string text = "rain wind rain sun cloud rain sun wind sun sun cloud rain fog sun wind";
    std::istringstream in(text);
    std::vector<std::string> words;
    for (std::string w; in >> w;) words.push_back(w);
    std::cout << "observations: " << words.size() << "\n";
    std::map<std::string, int> counts;
    for (const auto& w : words) ++counts[w];
    for (const auto& [w, n] : counts) std::cout << "  " << w << " " << n << "\n";
    std::set<std::string> kinds(words.begin(), words.end());
    std::cout << "distinct kinds: " << kinds.size() << "\n";
    std::vector<std::pair<std::string, int>> ranked(counts.begin(), counts.end());
    std::sort(ranked.begin(), ranked.end(), [](const auto& a, const auto& b) { return a.second != b.second ? a.second > b.second : a.first < b.first; });
    std::cout << "ranked: ";
    for (const auto& [w, n] : ranked) std::cout << w << "(" << n << ") ";
    std::cout << "\n";
    std::unordered_map<std::string, int> fast(counts.begin(), counts.end());
    std::cout << "unordered lookup sun: " << fast.at("sun") << ", has hail: " << fast.contains("hail") << ", map[\"hail\"] creates it: " << counts["hail"] << " -> size now " << counts.size() << "\n";
    std::vector<std::string> dry = words;
    dry.erase(std::remove_if(dry.begin(), dry.end(), [](const std::string& w) { return w == "rain" || w == "fog"; }), dry.end());
    std::cout << "after erase-remove of rain and fog: " << dry.size() << " left\n";
    std::vector<int> nums{5, 12, 7, 20, 3, 15};
    auto mid = std::partition(nums.begin(), nums.end(), [](int x) { return x >= 10; });
    std::cout << "partition: " << (mid - nums.begin()) << " values are >= 10\n";
    std::vector<int> doubled(nums.size());
    std::transform(nums.begin(), nums.end(), doubled.begin(), [](int x) { return x * 2; });
    int total = 0; for (int x : doubled) total += x;
    std::cout << "sum of doubled values: " << total << "\n";
}
observations: 15
  cloud 2
  fog 1
  rain 4
  sun 5
  wind 3
distinct kinds: 5
ranked: sun(5) rain(4) wind(3) cloud(2) fog(1) 
unordered lookup sun: 5, has hail: 0, map["hail"] creates it: 0 -> size now 6
after erase-remove of rain and fog: 10 left
partition: 3 values are >= 10
sum of doubled values: 124

The text holds 15 observations and 5 distinct kinds. The map counted them with ++counts[word], and since a std::map is sorted, the counts print in alphabetical order: {‘cloud’: 2, ‘fog’: 1, ‘rain’: 4, ‘sun’: 5, ‘wind’: 3}. To rank by frequency, the program copied the pairs into a vector and sorted them with a lambda that compares counts first and names second, so ties have a fixed order: sun(5) rain(4) wind(3) cloud(2) fog(1). A hash map gives the same lookups, here 5 for sun, without any order. The surprise is the line with hail: map[“hail”] on a missing key quietly inserted it with a count of zero, so the map grew from five to 6 entries, which is why you should use find, contains or at when you only want to look.

The erase-remove idiom removed every rain and fog from a copy of the words, leaving 10 of 15. The partition put the values of at least 10 first, and there are 3 of them, and the transform doubled each value into another vector, which adds up to 124. Algorithms like these state what you mean, and they have been tested by everyone who uses the library.

Check by hand: rain appears 4 times, sun 5, wind 3, cloud 2 and fog once, which adds to 15. Python’s collections.Counter gave {‘cloud’: 2, ‘fog’: 1, ‘rain’: 4, ‘sun’: 5, ‘wind’: 3}, and its ranking by count then name matches the program. In the list 5, 12, 7, 20, 3, 15, the values of at least 10 are 12, 20 and 15, which are three, and the sum of all six is 62, so doubled it is 124.

map[] inserts missing keys

Reading a missing key with operator[] adds it with a default value. Use find, contains or at when you only want to look, or you will grow the map by accident.

Prefer algorithms to hand-written loops

std::sort, std::find_if, std::count_if and std::transform say what you mean and avoid off-by-one mistakes. In C++20, std::erase_if(v, pred) replaces the erase-remove idiom.

About this course

Every program in this lesson was compiled with GCC 13 using -std=c++20 -Wall -Wextra and run while the course was written. C++ has a new standard every three years and compilers differ in what they support, so check your compiler’s documentation and cppreference.com for the current state. contains on unordered_map needs C++20.

Practice

Find the longest run of the same weather word in the text. Use a std::set to list the words that occur exactly once. Rewrite the erase-remove line with std::erase_if and compare.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

Which container keeps its keys sorted?

  1. std::map
  2. std::unordered_map
  3. std::vector
  4. std::array

Sorted by key.

What happens when you read counts[“hail”] on a missing key?

  1. It throws
  2. It returns garbage
  3. It crashes
  4. It inserts the key with zero

The map grew.

What does the erase-remove idiom do?

  1. Sorts a vector
  2. Copies a vector
  3. Reverses a vector
  4. Removes matching elements from a vector

remove_if then erase.

Why break ties by name in the sort?

  1. To make it faster
  2. It is required
  3. To make the order the same every time
  4. To remove items

Counts alone leave ties unordered.

What does std::partition do?

  1. Sorts
  2. Deletes
  3. Moves matching elements to the front
  4. Copies

It returns the partition point.

Summary

  • map, unordered_map and set cover most lookup needs.
  • Algorithms take iterator ranges, and ranges in C++20 take containers.
  • Erase-remove deletes matching elements from a vector.
  • map[] inserts missing keys.

Next lesson

Lesson 13 introduces templates and concepts.

Questions

When should I use unordered_map?

When you do not need order and want fast lookups on average. Use map when you need sorted iteration or ordered ranges.

What is a comparator?

A function that says whether one element should come before another. sort uses it, and so do map and set.

Do algorithms work on arrays?

Yes. Raw pointers are iterators too, so std::sort(arr, arr + n) works.

Progress is saved in this browser.