Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map/unordered_map: Prefer find() and then at() or try at() catch out_of_range?

When using std::map or std::unordered_map, what is the preferable way to access an element that might not be in the container? Should one ask permission or ask for forgiveness? Why?

That is,

if (mymap.find(key) != mymap.end()) {
    value = mymap.at(key);
    // do stuff
}
else {
    // do something else
}

vs.

try {
    value = mymap.at(key);
    // do stuff
}
catch(const std::out_of_range& oor) {
    // do something else
}
like image 948
Praxeolitic Avatar asked Aug 05 '14 17:08

Praxeolitic


People also ask

What is the complexity of find in unordered_map?

Return values: If the given key exists in unordered_map it returns an iterator to that element otherwise it returns the end of the map iterator. // find function in unordered_map. Time Complexity : O(1) on average.

How does find work in unordered_map?

The C++ function std::unordered_map::find() finds an element associated with key k. If operation succeeds then methods returns iterator pointing to the element otherwise it returns an iterator pointing the map::end().

How do you check if a value exists in an unordered_map?

To check for the existence of a particular key in the map, the standard solution is to use the public member function find() of the ordered or the unordered map container, which returns an iterator to the key-value pair if the specified key is found, or iterator to the end of the container if the specified key is not ...

Which is more efficient map or unordered_map?

Insertion of spread keys in std::map tends to outperform std::unordered_map when map size is under 10000 elements. Insertion of dense keys in std::map doesn't present performance difference with std::unordered_map under 1000 elements. In all other situations std::unordered_map tends to perform faster.


1 Answers

I suggest secret option C which avoids both non-exceptional exceptions AND doing the search twice:

MyMapType::const_iterator iter = mymap.find(key);

if(iter != mymap.end())
{
    // iter is item pair in the map. The value will be accessible as `iter->second`.
}

In C++ it is not idiomatic to use exception handling for flow control, which is what the second code example is doing. It will make it harder for maintainers to understand the code and, depending on the specific compiler, it may not perform as well.

like image 124
Mark B Avatar answered Oct 21 '22 10:10

Mark B