I'm implementing a locking mecahnism and for this I need a fast lookup wether a given Id already is locked. Now I was thinking of using a map and I'm wondering if there is some better structure for this. Basically I don't really need the map, because there is no mapping done. However, If I would use a vector, I would have to do a linear search, which would become expensive for many entries.
Now I wonder if there is some structure that allows me a similar fast lookup without the additional overhead of storing etra data.
std::map<IdType, bool> locked;
// Prevent deadlock by checking if this thread already locked. Otherwise
// it can pass through.
if(locked.find(Id) != locked.end())
If you have C++0x, you could use
std::unordered_set, average lookup is O(1).
From the cppreference.com documentation (emphasis mine):
... Search, insertion, and removal have average constant-time complexity.
Internally, the elements are not sorted in any particular order, but organized into buckets. Which bucket an element is placed into depends entirely on the hash of its value. This allows fast access to individual elements, since once a hash is computed, it refers to the exact bucket the element is placed into.
#include <tr1/unordered_set> std::tr1::unordered_set<IdType> locked;
You could also use an
unordered_map, but I guess the readers of you code would have a hard time understanding what the mapped value is used for.
P.S.: And keep the Rules Of Optimization in mind ;)