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.
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().
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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With