Cover Image for Std partition point in C++
156 views

Std partition point in C++

The std::partition_point is a function available in the Standard Library as part of the C++17 standard and later. It is used to find the partition point of a sorted range, which means the first element in the range that does not satisfy a given predicate.

Here’s the syntax for std::partition_point:

template <class ForwardIt, class UnaryPredicate>
ForwardIt partition_point(ForwardIt first, ForwardIt last, UnaryPredicate p);
  • first and last define the range of elements you want to search within.
  • p is a unary predicate function or functor. The function should return true for elements that satisfy the condition and false for those that don’t.

The std::partition_point function returns an iterator to the first element in the range for which the predicate p returns false. If all elements satisfy the predicate, it returns last.

Here’s a simple example demonstrating how to use std::partition_point:

C++
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};

    // Define a predicate: Find the first number greater than or equal to 5.
    auto predicate = [](int num) {
        return num >= 5;
    };

    // Find the partition point using std::partition_point.
    auto it = std::partition_point(numbers.begin(), numbers.end(), predicate);

    if (it != numbers.end()) {
        std::cout << "Partition point found: " << *it << std::endl;
    } else {
        std::cout << "All elements satisfy the condition." << std::endl;
    }

    return 0;
}

In this example, std::partition_point is used to find the partition point of a sorted vector of numbers. The predicate checks if each element is greater than or equal to 5. The function returns an iterator to the first element that doesn’t satisfy this condition, which is 6 in this case.

Remember that std::partition_point assumes that the input range is already sorted based on the predicate. If the range is not sorted, the behavior is undefined.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS