How do you check that an element is in a set?
Is there a simpler equivalent of the following code:
myset.find(x) != myset.end()
std::set is an associative container that contains a sorted set of unique objects of type Key . Sorting is done using the key comparison function Compare. Search, removal, and insertion operations have logarithmic complexity. Sets are usually implemented as red-black trees.
Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific sorted order i.e. either ascending or descending.
The typical way to check for existence in many STL containers such as std::map
, std::set
, ... is:
const bool is_in = container.find(element) != container.end();
Another way of simply telling if an element exists is to check the count()
if (myset.count(x)) { // x is in the set, count is 1 } else { // count zero, i.e. x not in the set }
Most of the times, however, I find myself needing access to the element wherever I check for its existence.
So I'd have to find the iterator anyway. Then, of course, it's better to simply compare it to end
too.
set< X >::iterator it = myset.find(x); if (it != myset.end()) { // do something with *it }
C++ 20
In C++20 set gets a contains
function, so the following becomes possible as mentioned at: https://stackoverflow.com/a/54197839/895245
if (myset.contains(x)) { // x is in the set } else { // no x }
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