C++ std::map::try_emplace
Register the first customer for a seat without replacing an existing reservation.
A simple example
std::map::try_emplace
- Start with A = 1
- Do this Insert A = 2 only if absent
- Result A stays 1
Syntax
seats.try_emplace(key, name)
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
./lessonKeep the first reservation for a seat
Two students ask for the same seat at a school play. The desk enters the requests in order and needs the first confirmed student's name to survive the second request.
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, std::string> seats;
seats.try_emplace("A1", "Mira");
seats.try_emplace("A1", "Sam");
std::cout << seats.at("A1");
return 0;
}
Mira
Mira arrives before Sam and keeps the reservation for A1.
Reserve the kiln
Two potters ask to use the same afternoon slot. Two people claim the same slot in order. Keep the first recorded name and read it after both requests.
Assign a library carrel
Two students request the only window desk. Two people claim the same slot in order. Keep the first recorded name and read it after both requests.
What to watch for
The operation leaves an existing mapping intact. Inspect the returned boolean if the desk needs to confirm which request won.