C++ std::map::erase by iterator
Release a locker after checking that its current owner is the student returning it.
A simple example
std::map::erase by iterator
- Start with A = 1
- Do this Remove A if its value is 1
- Result A is absent
Syntax
claims.erase(it)
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
./lessonRelease a locker only for its recorded owner
A school uses locker numbers as keys and student names as values. When Mira returns her locker, the desk clears the assignment only if the current register still names Mira.
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, std::string> claims{{"L2", "Mira"}};
auto it = claims.find("L2");
if (it != claims.end() && it->second == "Mira") {
claims.erase(it);
std::cout << "Released";
}
return 0;
}
Released
Locker L2 belongs to Mira, so the register accepts the return.
Return a locker key
A locker has a single claim and its registered holder returns the key. The clerk removes the claim only when the recorded owner matches the claimant. How many claims remain?
Keep a reserved headset
A different student tries to release the only headset claim. The clerk removes the claim only when the recorded owner matches the claimant. How many claims remain?
What to watch for
Only erase a valid iterator. The iterator to the erased entry becomes invalid.