To sort items of a Set in C++, you can copy the Set elements to a vector and use the std::sort
algorithm.
In this example,
numberSet
containing integer values.numbers
and copy the elements of numberSet
into it.std::sort
algorithm from the <algorithm>
header.#include <iostream>
#include <set>
#include <vector>
#include <algorithm>
int main() {
std::set<int> numberSet = {5, 3, 8, 1, 2};
std::vector<int> numbers(numberSet.begin(), numberSet.end());
std::sort(numbers.begin(), numbers.end());
for (const auto& num : numbers) {
std::cout << num << " ";
}
return 0;
}
1 2 3 5 8
In this example,
stringSet
containing string values.strings
and copy the elements of stringSet
into it.std::sort
algorithm from the <algorithm>
header.#include <iostream>
#include <set>
#include <vector>
#include <algorithm>
#include <string>
int main() {
std::set<std::string> stringSet = {"banana", "apple", "cherry", "date"};
std::vector<std::string> strings(stringSet.begin(), stringSet.end());
std::sort(strings.begin(), strings.end());
for (const auto& str : strings) {
std::cout << str << " ";
}
return 0;
}
apple banana cherry date
In this tutorial, we learned How to Sort Items of a Set in C++ language with well detailed examples.