To check if a specific item is present in a Set in C++, you can use the find
method.
In this example,
mySet
containing elements of a specific type.find
method of the Set to check if a specific item is present.find
method returns an iterator pointing to the found element if the item is present in the Set, otherwise it returns an iterator pointing to the end of the Set.#include <iostream>
#include <set>
int main() {
// Define Set with items
std::set<std::string> mySet = {"apple", "banana", "orange", "grape", "melon"};
// Check if item is present
std::string item = "banana";
bool isPresent = mySet.find(item) != mySet.end();
// Print result
std::cout << "Is " << item << " present in the Set? " << (isPresent ? "true" : "false") << std::endl;
return 0;
}
Is banana present in the Set? true
In this example,
mySet
containing elements of a specific type.find
method of the Set to check if a specific item is not present.find
method returns an iterator pointing to the found element if the item is present in the Set, otherwise it returns an iterator pointing to the end of the Set.#include <iostream>
#include <set>
int main() {
// Define Set with items
std::set<std::string> mySet = {"apple", "banana", "orange", "grape", "melon"};
// Check if item is not present
std::string item = "peach";
bool isNotPresent = mySet.find(item) == mySet.end();
// Print result
std::cout << "Is " << item << " not present in the Set? " << (isNotPresent ? "true" : "false") << std::endl;
return 0;
}
Is peach not present in the Set? true
In this tutorial, we learned How to check if a Specific Item is present in the Set in C++ language with well detailed examples.