C++ std::map::insert_or_assign
Update a shelf count and retrieve it using the product label.
A simple example
std::map::insert_or_assign
- Start with A = 1
- Do this Store 2 at key A
- Result A = 2
Syntax
stock.insert_or_assign(key, count)
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
./lessonUpdate the count for a shelf label
A shop keeps one inventory entry for each shelf label. After a second delivery arrives, the clerk replaces the old tea count and looks up the current total using the same label.
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> stock{{"Tea", 3}};
stock.insert_or_assign("Tea", 7);
std::cout << stock.at("Tea");
return 0;
}
7
Updating the Tea key changes the recorded count from three to seven.
Revise a locker assignment
A rental desk moves the green key from locker 6 to locker 9. The operator assigns the new value to the existing key and reads it back. Which value does the key now hold?
Correct a menu price
A café changes its soup price after reprinting the menu. The operator assigns the new value to the existing key and reads it back. Which value does the key now hold?
What to watch for
Use at for a checked read. Reading through operator[] can create a default entry.