Ensuring that your sets are sorted correctly before using set algorithms is crucial for their correct operation. Most set algorithms in the C++ Standard Library, such as std::ranges::set_union()
, std::ranges::set_intersection()
, and std::ranges::set_difference()
, require sorted inputs to function correctly.
You can use the std::sort()
function to sort your sets before passing them to set algorithms. Here’s how to do it:
<algorithm>
for sorting and set operations.std::sort()
to sort your containers.Here’s an example:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> A{3, 1, 4, 1, 5};
std::vector<int> B{5, 9, 2, 6, 5};
std::vector<int> Results;
Results.resize(A.size() + B.size());
// Sort the inputs
std::sort(A.begin(), A.end());
std::sort(B.begin(), B.end());
// Perform the set union
auto [AEnd, BEnd, UnionEnd] =
std::ranges::set_union(A, B, Results.begin());
Results.erase(UnionEnd, Results.end());
for (auto x : Results) {
std::cout << x << ", ";
}
}
1, 1, 2, 3, 4, 5, 5, 6, 9,
If you need a custom order, you can use a custom comparator with std::sort()
:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> A{3, 1, 4, 1, 5};
std::vector<int> B{5, 9, 2, 6, 5};
std::vector<int> Results;
Results.resize(A.size() + B.size());
// Custom comparator for descending order
auto Comparer = [](const int& a, const int& b) {
return a > b;
};
// Sort the inputs
std::sort(A.begin(), A.end(), Comparer);
std::sort(B.begin(), B.end(), Comparer);
// Perform the set union
auto [AEnd, BEnd, UnionEnd] =
std::ranges::set_union(
A, B, Results.begin(), Comparer);
Results.erase(UnionEnd, Results.end());
for (auto x : Results) {
std::cout << x << ", ";
}
}
9, 6, 5, 5, 4, 3, 2, 1, 1,
After sorting, it’s good practice to verify that your sets are sorted correctly:
#include <algorithm>
#include <iostream>
#include <vector>
bool is_sorted(const std::vector<int>& vec) {
return std::is_sorted(vec.begin(), vec.end());
}
int main() {
std::vector<int> A{3, 1, 4, 1, 5};
std::sort(A.begin(), A.end());
if (is_sorted(A)) {
std::cout << "A is sorted";
} else {
std::cout << "A is not sorted";
}
}
A is sorted
std::sort()
to ensure your inputs are sorted.std::is_sorted()
.Correctly sorting your sets ensures that set algorithms work as expected and produce correct results.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to set algorithms, and how to implement them using the C++ standard library