Library contents

C++ map::find with a fallback

Display a fallback stock count for an item missing from the ledger.

A simple example

map::find with a fallback

  1. Start with Map with A = 2
  2. Do this Read missing B with fallback 0
  3. Result 0
The lookup supplies zero because B has no stored value.

Syntax

C++ syntax
stock.find(item)
Run these examples in C++

Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.

c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson

Show a balance for an item never received

A kiosk receives its first delivery of pencils but has yet to receive any rulers. Its stock display should show zero for rulers while keeping the ledger limited to products actually received.

Result0 on hand, 1 product
lesson.cpp
#include <iostream>
#include <map>
#include <string>

int main() {
    const std::map<std::string, int> stock{{"Pencil", 12}};
    auto item = stock.find("Ruler");
    int on_hand = item == stock.end() ? 0 : item->second;
    std::cout << on_hand << " on hand, " << stock.size() << " product";
    return 0;
}
Output
0 on hand, 1 product

The display shows zero for rulers. The original pencil entry is still the only product in the ledger.

Advertisements

Look up a borrowed tripod

The equipment desk has a two-day loan period for a camera, but no special period for a tripod. The system uses the recorded value when present and the displayed fallback otherwise. Which value reaches the screen?

Giventripod missing · default 7 days
Worked result7

Read a room preference

The timetable stores a room choice for the choir club. The system uses the recorded value when present and the displayed fallback otherwise. Which value reaches the screen?

Givenchoir → Hall · default Studio
Worked resultHall

What to watch for

A missing find result compares equal to end(). Subscript lookup on a mutable map would insert a missing key.

Documentation for map::find with a fallback