The partition_copy()
algorithm is useful when you need to partition a collection into two separate containers without modifying the original container.
This is in contrast to partition()
and stable_partition()
, which rearrange elements in place. Here are some common use cases for partition_copy()
:
If you need to maintain the original collection for further use or comparisons, partition_copy()
allows you to create new partitions without altering the original data.
When you need the partitions to exist in separate containers, partition_copy()
provides a clean and efficient way to achieve this. For example, you might want to separate even and odd numbers into two different vectors:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> A = {1, -6, 4, 2, 5, 7};
std::vector<int> Even;
std::vector<int> Odd;
Even.resize(A.size());
Odd.resize(A.size());
auto isEven = [](int x) { return x % 2 == 0; };
auto result = std::ranges::partition_copy(
A, Even.begin(), Odd.begin(), isEven);
// Adjusting sizes of Even and Odd vectors
// based on the result
Even.resize(result.out1 - Even.begin());
Odd.resize(result.out2 - Odd.begin());
std::cout << "Original: ";
for (int x : A) std::cout << x << ", ";
std::cout << "\nEven: ";
for (int x : Even) std::cout << x << ", ";
std::cout << "\nOdd: ";
for (int x : Odd) std::cout << x << ", ";
}
Original: 1, -6, 4, 2, 5, 7,
Even: -6, 4, 2,
Odd: 1, 5, 7,
If your algorithm requires the original data and the partitions to be processed in parallel or by different functions, keeping them in separate containers can simplify memory management and reduce the risk of accidental modifications.
Some algorithms or processing steps might require the data to be in separate containers for performance or design reasons. Using partition_copy()
can help in such scenarios by directly producing the required data structure.
Use partition_copy()
when you need to keep the original collection unchanged and want the partitions to exist in separate containers. It’s particularly useful for preserving original data, managing memory more effectively, and complying with specific algorithmic constraints.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to partitions, and the C++ standard library algorithms that create them