In the scenario you describe (m1.erase(2);
vs. m1.erase(m1.find(2));
), the two methods are should be entirely equivalent, give or take the cost of creating and returning iterators, though this depends on your STL implementation.
The point of erase by iterator
is to remove an entry from the key, when you already have an iterator because of other operations your program needed to execute on the element this iterator refers to. For instance:
void processEntry(const std::pair<int, double>& p) {
// do something like maybe writing it to a file
}
std::map<int, double> m1 = { { 1, 1.1 }, { 2, 2.2 }, { 3, 3.3 } };
const auto it = std::find_if(m1.begin(), m1.end(), [](const std::pair<int, double>& p) {
return p.first > 1 && p.second < 3.0;
});
if (it != m1.end()) {
processEntry(*it);
m1.erase(it);
}