HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcppCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howchecksetstdelementthat

Problem

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

Code Snippets

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

Context

Stack Overflow Q#1701067, score: 600

Revisions (0)

No revisions yet.