The partition_point()
algorithm is used to find the boundary between two partitions in a range that has been partitioned.
This boundary is the point where elements satisfying the predicate (returning true
) end, and those not satisfying the predicate (returning false
)Â begin.
partition_point()
takes a range and a predicate as arguments. It returns an iterator to the first element in the range that does not satisfy the predicate.
This iterator marks the start of the second partition. Here’s an example:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> A = {2, -6, 4, 1, -5, 3};
auto isEven = [](int x) { return x % 2 == 0; };
auto PartitionPoint =
std::ranges::partition_point(A, isEven);
std::cout << "The first element in the second"
" partition is " << *PartitionPoint << "\n";
std::cout << "First partition: ";
for (auto it = A.begin();
it != PartitionPoint; ++it) {
std::cout << *it << ", ";
}
std::cout << "\nSecond partition: ";
for (auto it = PartitionPoint;
it != A.end(); ++it) {
std::cout << *it << ", ";
}
}
The first element in the second partition is 1
First partition: 2, -6, 4,
Second partition: 1, -5, 3,
partition_point()
to work correctly. If the range is not properly partitioned, the result may be incorrect.partition_point()
will return an iterator to the end of the range.The partition_point()
function is useful in scenarios where you need to quickly locate the boundary between partitions without rechecking the entire range. This can be particularly efficient in large datasets where partitioning has already been performed.
In summary, partition_point()
helps in finding the exact point of separation between two partitions in a partitioned range, providing an efficient way to navigate and manipulate partitioned data.
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