Search code examples
c++stlunordered-set

Alternative to find() for determining whether an unordered_set contains a key


Suppose I have an unordered_set<int> S and I wanna to check if it contains a certain int x.

Is there a way for me to write something like if(S.contains(x)){ /* code */ } that works like if(S.find(x) != S.end()){ /* code */ } ?

It can be a macro or anything but I just find it ugly and unnecessarily long to write a simple lookup method like that.


Solution

  • Instead of using std::unordered_set's find() member function for determining whether a given key x is present as in:

    if (S.find(x) != S.end()) { /* code */ }
    

    you can simply use the count() member function:

    if (S.count(x)) { /* code */ }
    

    An std::unordered_set does not allow duplicates, so count() will return either 0 or 1.


    The unordered_set::count() member function shouldn't be less efficient than unordered_set::find() since the traversal of the elements for finding out the count of the requested key can be stopped as soon as one is found because there can't be duplicates.