How to check that an element is in a std::set?
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
}
Just to clarify, the reason why there is no member like contains()
in these container types is because it would open you up to writing inefficient code. Such a method would probably just do a this->find(key) != this->end()
internally, but consider what you do when the key is indeed present; in most cases you'll then want to get the element and do something with it. This means you'd have to do a second find()
, which is inefficient. It's better to use find directly, so you can cache your result, like so:
auto it = myContainer.find(key);
if (it != myContainer.end())
{
// Do something with it, no more lookup needed.
}
else
{
// Key was not present.
}
Of course, if you don't care about efficiency, you can always roll your own, but in that case you probably shouldn't be using C++... ;)