We have just found a bug in our code, that goes something like this:
class foo {
unordered_map<int,string> m_someMap;
public:
void stuff() {
unordered_map<int, string> someMap;
...
auto it = someMap.find(x);
if (it != m_someMap.end()) { // oops! comparing to the end() of a wrong map!
// found x in the map, use it->second here
}
}
}
The obvious problem here is that checking if find() succeeded requires naming the map twice, and if those two occurrences went out of sync, user beware.
What is the best practice to prevent this? In other words, how can I check that an item is present in a map without having to say the map's name twice?
I wish map iterators were convertible to bool, so I could write simple if (it)..., but they aren't.
Any other ideas? safe_find() template function that returns an optional<unordered_map<int,string>::iterator>>? Some magic form the modern standard library?
Do you need to check only for existence of given key, or do sth with the found element too? There's a plethora of options, depending on what is to be achieved and lanaguage version in use.
https://godbolt.org/z/q1qbxKMs7
map::containsmapObject.contains(key);from C++20. Returns a bool.map::countmapObject.count(key) > 0;pre C++20 way of point two. Slightly uglier, but works.map::attry { mapObject.at(key); } catch (const std::out_of_range& ex) {//handle ex here}Exception based, therefore oftentimes disliked or discouraged, but works.