To iterate over a set in C++, you can use a range-based for loop.
In this example,
stringSet
containing various strings.stringSet
.#include <iostream>
#include <set>
int main() {
std::set<std::string> stringSet = {"Apple", "Banana", "Orange"};
for (const std::string& str : stringSet) {
std::cout << str << std::endl;
}
return 0;
}
Apple Banana Orange
In this example,
intSet
containing various integer values.intSet
.#include <iostream>
#include <set>
int main() {
std::set<int> intSet = {1, 2, 3, 4, 5};
for (int num : intSet) {
std::cout << num * 2 << std::endl;
}
return 0;
}
2 4 6 8 10
In this tutorial, we learned How to Iterate Over a Set in C++ language with well detailed examples.