How to check that an element is in a std::set?


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()
6/12/2011 10:23:24 PM

Accepted Answer

The typical way to check for existence in many STL containers is:

const bool is_in = container.find(element) != container.end();
11/9/2009 5:39:19 PM

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

if (myset.contains(x)) {
  // x is in the set
} else {
  // no x 

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow