Open In App

How to Check If a Set Contains an Element in C++?

Last Updated : 22 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, a set is an associative container in which each element has to be unique. In this article, we will learn how to check that an element is in a std::set in C++.

Example

Input:
mySet = { "Hydrogen", "Oxygen",
                   "Sulphur", "Nitrogen", "Manganese"}
Search Element: Nitrogen

Output:
Nitrogen exists in the given set

Check if an Element is Present in a Set in C++

To check if a set contains a specific element or not, we can use the set::find() function that takes the element to be searched as a parameter and returns an iterator pointing to that element if the element is found, or returns an iterator pointing to std::set::end if the element is not found.

C++ Program to Check if an Element is Present in a Set in C++

The below example demonstrates how we can use the find() function to check if the given element is present in the set or not.

C++




// C++ program to Check if a Set Contains a Specific Element
#include <iostream>
#include <set>
#include <string>
using namespace std;
  
int main()
{
    // Declare set of 5 Strings - chemicals
    set<string> chemicals
        = { "Hydrogen", "Oxygen", "Sulphur", "Nitrogen",
            "Manganese" };
  
    // declaring specific element to be searched
    string searchElement = "Sulphur";
  
    // Searching specific element in the chemicals set
    auto it1 = chemicals.find(searchElement);
  
    // Check if Set contains the value "Sulphur"
    if (it1 == chemicals.end()) {
        cout << searchElement
             << " does not exist in a given set" << endl;
    }
    else {
        cout << searchElement << " exists in a given set"
             << endl;
    }
  
    return 0;
}


Output

Sulphur exists in a given set

Time Complexity: O(log n)
Auxiliary Space: O(1)

Note: We can also use set::count() function to check if a set contains a specific element.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads