Check if an element is present in a set in C++
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <unordered_set> using namespace std; int main() { std::unordered_set<int> s = { 1, 2, 3, 4, 5 }; int key = 3; if (s.find(key) != s.end()) { std::cout << "Element is present in the set" << std::endl; } else { std::cout << "Element not found" << std::endl; } return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <unordered_set> using namespace std; int main() { std::unordered_set<int> s = { 1, 2, 3, 4, 5 }; int key = 3; if (s.count(key)) { std::cout << "Element is present in the set" << std::endl; } else { std::cout << "Element not found" << std::endl; } return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
#include <iostream> #include <unordered_set> using namespace std; int main() { std::unordered_set<int> s = { 1, 2, 3, 4, 5 }; int key = 3; bool found = false; for (auto const &e: s) { if (e == key) { found = true; break; } } if (found) { std::cout << "Element is present in the set" << std::endl; } else { std::cout << "Element not found" << std::endl; } return 0; } |
Output:
Element is present in the set
That’s all about determining whether an element is present in a set in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)