Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 898
Daniel Avatar asked Dec 15 '18 18:12

Daniel


People also ask

How do you check if an element is present in an unordered_set in C++?

The unordered_set::find() function is a built-in function in C++ STL which is used to search for an element in the container. It returns an iterator to the element, if found else, it returns an iterator pointing to unordered_set::end().

How do you check if an element is present in a set?

Using find() function The standard solution to check for existence of an element in the set container ( std::set or std::unordered_set ) is to use its member function find() . If the specified element is found, an iterator to the element is returned; otherwise, an iterator to the end of the container is returned.

What is the difference between a set and an unordered_set?

Sets vs Unordered SetsSet is an ordered sequence of unique keys whereas unordered_set is a set in which key can be stored in any order, so unordered. Set is implemented as a balanced tree structure that is why it is possible to maintain order between the elements (by specific tree traversal).


2 Answers

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.

like image 71
ネロク・ゴ Avatar answered Oct 02 '22 01:10

ネロク・ゴ


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.

like image 21
Hanzhou Tang Avatar answered Oct 02 '22 02:10

Hanzhou Tang