How to Check If a Set Contains an Element in C++?
Last Updated :
22 Feb, 2024
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++
#include <iostream>
#include <set>
#include <string>
using namespace std;
int main()
{
set<string> chemicals
= { "Hydrogen" , "Oxygen" , "Sulphur" , "Nitrogen" ,
"Manganese" };
string searchElement = "Sulphur" ;
auto it1 = chemicals.find(searchElement);
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.
Share your thoughts in the comments
Please Login to comment...