C++ Conditional update with map::find
Replace a room assignment only when the change slip matches the current entry.
A simple example
Conditional update with map::find
- Start with A = 1
- Do this Replace 1 with 2 if it still matches
- Result A = 2
Syntax
if (it != rooms.end() && it->second == expected)
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
./lessonChange a room assignment only if it is still current
A receptionist holds a change slip that moves a class from room A2 to B1. Before updating the board, she checks that the displayed entry still matches the room printed on her slip.
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, std::string> rooms{{"Class", "A2"}};
auto it = rooms.find("Class");
if (it != rooms.end() && it->second == "A2") it->second = "B1";
std::cout << rooms.at("Class");
return 0;
}
B1
The old assignment is A2, so the change to B1 goes through.
Change a duty room
The old assignment still matches the room printed on the request. The desk replaces the value only when the recorded value matches the expected one. Which value remains?
Ignore a stale booking change
A newer room assignment has already been saved. The desk replaces the value only when the recorded value matches the expected one. Which value remains?
What to watch for
Compare the iterator with end before accessing its value.