This post will discuss how to check if an element is present in a set in C++.

1. Using find() function

The standard solution to check for existence of an element in the set container (std::set or std::unordered_set) is to use its member function find(). If the specified element is found, an iterator to the element is returned; otherwise, an iterator to the end of the container is returned.

Download  Run Code

Output:

Element is present in the set

2. Using count() function

Another good alternative is to use the count() function of the set container. It returns value 1 if the element is found in the set container, otherwise 0 is returned.

Download  Run Code

Output:

Element is present in the set

3. Naive Solution

We can also write our own routine for this. The idea is to iterate through the contents of the set using a range-based for-loop and compare each element against the given key.

Download  Run Code

Output:

Element is present in the set

That’s all about determining whether an element is present in a set in C++.