Let's say I'm trying to check if an item exists in an associative container, and do something to it if it does. The simple way to do this is as follows:
std::unordered_map<std::string, Whatever> thisIsAMap;
// C++17
if (thisIsAMap.count("key") > 0u) { doThing(thisIsAMap["key"]); }
// C++20
if (thisIsAMap.contains("key")) { doThing(thisIsAMap["key"]); }
However, this has always seemed somewhat wasteful to me, as it involves finding the same item twice, which might be quite an expensive operation. Instead, I tend to do this:
auto found = thisIsAMap.find("key");
if (found != thisIsAMap.end()) { doThing(found->second); }
This only requires finding the item once, and then using it.
Is the latter approach actually any better? Are there any good reasons to use either approach over the other?