diff --git a/ch11/ex11_31.cpp b/ch11/ex11_31.cpp index 4dd2cd54..ca340c47 100644 --- a/ch11/ex11_31.cpp +++ b/ch11/ex11_31.cpp @@ -10,9 +10,9 @@ // Be sure your program works correctly if the element you look for is not in // the map. +#include #include #include -#include using std::string; @@ -20,20 +20,18 @@ int main() { std::multimap authors{ {"alan", "DMA"}, {"pezy", "LeetCode"}, {"alan", "CLRS"}, - {"wang", "FTP"}, {"pezy", "CP5"}, {"wang", "CPP-Concurrency"}}; - // want to delete an element that author is [Alan], work is [112]. + {"wang", "FTP"}, {"pezy", "CP5"}, {"wang", "CPP-Concurrency"}, + {"pezy", "CP5"}}; + // want to delete an element that author is [pezy], work is [CP5]. string author = "pezy"; string work = "CP5"; - auto found = authors.find(author); - auto count = authors.count(author); - while (count) { - if (found->second == work) { - authors.erase(found); - break; - } - ++found; - --count; + for (auto found = authors.find(author); + found != authors.end() && found->first == author;) { + if (found->second == work) + found = authors.erase(found); + else + ++found; } for (const auto& author : authors)