Learning Hub Search Ctrl K

Modern C++ › C++11

unordered containers, chrono and random

Hash containers, time utilities and the <random> library.

Since C++11 intermediate #unordered_map#unordered_set#hash#chrono#random#mt19937#distributions

Explanation

Three library additions every C++11 program ends up using.

Unordered containers (unordered_map, unordered_set, and multi versions) are hash tables: average O(1) lookup/insert versus O(log n) for map/set, but no ordering. They need a hash function (std::hash<K>, provided for built-in types and std::string) and == on the key. Use map when you need sorted iteration or ranges.

<chrono> gives type-safe time: durations (std::chrono::milliseconds), time points, and clocks (steady_clock for measuring intervals, system_clock for wall time). Units are in the type, so conversions are checked and explicit.

<random> replaces the poor rand(): an engine (std::mt19937) generates raw bits and a distribution (uniform_int_distribution, normal_distribution, …) shapes them. Seed the engine once, from std::random_device.

Example

#include <chrono>
#include <iostream>
#include <random>
#include <string>
#include <unordered_map>
#include <unordered_set>

struct Point {
    int x, y;
    bool operator==(const Point& o) const { return x == o.x && y == o.y; }
};
struct PointHash {                                     // custom hash for a custom key
    std::size_t operator()(const Point& p) const {
        return std::hash<int>()(p.x) * 31 + std::hash<int>()(p.y);
    }
};

int main() {
    std::unordered_map<std::string, int> count;
    for (const char* w : {"a", "b", "a", "c", "a"}) ++count[w];
    std::cout << count["a"] << " " << count.count("z") << " " << count.size() << "\n";   // 3 0 3

    std::unordered_set<Point, PointHash> seen;
    seen.insert({1, 2});
    seen.insert({1, 2});                                // duplicate ignored
    std::cout << seen.size() << "\n";                   // 1

    std::mt19937 gen{std::random_device{}()};           // engine, seeded once
    std::uniform_int_distribution<int> dice(1, 6);
    int roll = dice(gen);
    std::cout << "roll in range: " << (roll >= 1 && roll <= 6) << "\n";

    auto start = std::chrono::steady_clock::now();
    long long s = 0;
    for (int i = 0; i < 1000000; ++i) s += i;
    auto elapsed = std::chrono::steady_clock::now() - start;
    auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count();
    std::cout << "sum " << s << ", took >= 0 ms: " << (ms >= 0) << "\n";

    using namespace std::chrono;
    std::cout << duration_cast<seconds>(minutes(2) + seconds(30)).count() << "s\n";   // 150s
    return 0;
}

Common pitfalls

  • Iteration order of unordered containers is unspecified and can change after insertion (rehash). Don’t depend on it.
  • A bad hash function (e.g. returning a constant) degrades O(1) to O(n).
  • Rehashing invalidates iterators (but not references/pointers to elements).
  • Seeding mt19937 with a constant gives the same sequence every run (great for tests, wrong for games); creating a new engine per call defeats the randomness.
  • Use steady_clock to time code; system_clock can jump when the user changes the clock.
  • rand() % n has bias and low-quality bits. Use a distribution.

Legacy vs modern

C++98 only offered std::map/set (ordered), rand()/srand(), and C’s time()/clock(); hash tables came from std::tr1::unordered_map, SGI hash_map or Boost. C++17 adds try_emplace and extract for node handling; C++20 adds contains(), calendar/time-zone support in <chrono>.

Exercises

1. When would you choose std::map over std::unordered_map?

When you need keys in sorted order, range queries (lower_bound), or have no good hash for the key type.

2. Generate a random double in [0, 1).
std::mt19937 gen{std::random_device{}()};
std::uniform_real_distribution<double> d(0.0, 1.0);
double x = d(gen);