In C++, you can access items in a set using iteration or specific methods provided by the set data structure.
In this example,
stringSet
containing strings.#include <iostream>
#include <set>
#include <string>
int main() {
std::set<std::string> stringSet = {"Apple", "Banana", "Orange", "Grapes"};
for (const auto& item : stringSet) {
std::cout << item << std::endl;
}
return 0;
}
Apple Banana Orange Grapes
In this example,
numberSet
containing integers.size()
method to get the number of elements in the set.find()
method to check if an item exists in the set.#include <iostream>
#include <set>
int main() {
std::set<int> numberSet = {1, 2, 3, 4};
std::cout << "Number of elements: " << numberSet.size() << std::endl;
std::cout << "Does set contain 3? " << (numberSet.find(3) != numberSet.end() ? "true" : "false") << std::endl;
return 0;
}
Number of elements: 4 Does set contain 3? true
In this tutorial, we learned How to Access Items in a Set in C++ language with well detailed examples.