I’m looking for an elegant replacement to:
if (MyMap.count(x)) return MyMap[x];
While this code does what I want — it returns an entry if one exists — in the case where the element does exist, it searches the map twice. Is there a more elegant way?
std::map::find()returns aniterator.You can dereference the iterator it’s not
end()with no need to search themapagain.For a trivial example:
Perhaps not more elegant in terms of the amount of code, but more effcient than what you currently have.