Daniel
Daniel

Reputation: 7724

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.

Upvotes: 13

Views: 16032

Answers (2)

jfMR
jfMR

Reputation: 24738

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.

Upvotes: 20

Hanzhou Tang
Hanzhou Tang

Reputation: 391

I think you need if(S.count(x)){//do something}. According to cplusplus.com, the count function searches the container for elements with a value of k and returns the number of elements found. Because unordered_set containers do not allow for duplicate values, this means that the function actually returns 1 if an element with that value exists in the container, and zero otherwise.

Upvotes: 3

Related Questions