Search code examples
c++stlsetcontains

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()

Solution

  • Starting with C++20 you can use contains to check for existence in many STL containers such as std::map, std::set, ...:

    const bool is_in = container.contains(element);
    

    Pre C++20 the typical way was:

    const bool is_in = container.find(element) != container.end();