std::ranges::is_partitioned

Header: <algorithm>

  1. Returns true if all elements in the range [first,last) that satisfy the predicate pred after projection appear before all elements that don’t. Also returns true if [first,last) is empty.

# Declarations

Call signature
template< std::input_iterator I, std::sentinel_for<I> S,
class Proj = std::identity,
std::indirect_unary_predicate<std::projected<I, Proj>> Pred >
constexpr bool
is_partitioned( I first, S last, Pred pred, Proj proj = {} );

(since C++20)

template< ranges::input_range R, class Proj = std::identity,
std::indirect_unary_predicate<
std::projected<ranges::iterator_t<R>, Proj>> Pred >
constexpr bool
is_partitioned( R&& r, Pred pred, Proj proj = {} );

(since C++20)

# Parameters

# Return value

true if the range [first,last) is empty or is partitioned by pred, false otherwise.

# Example

#include <algorithm>
#include <array>
#include <iostream>
#include <numeric>
#include <utility>
 
int main()
{
    std::array<int, 9> v;
 
    auto print = [&v](bool o)
    {
        for (int x : v)
            std::cout << x << ' ';
        std::cout << (o ? "=> " : "=> not ") << "partitioned\n";
    };
 
    auto is_even = [](int i) { return i % 2 == 0; };
 
    std::iota(v.begin(), v.end(), 1); // or std::ranges::iota(v, 1);
    print(std::ranges::is_partitioned(v, is_even));
 
    std::ranges::partition(v, is_even);
    print(std::ranges::is_partitioned(std::as_const(v), is_even));
 
    std::ranges::reverse(v);
    print(std::ranges::is_partitioned(v.cbegin(), v.cend(), is_even));
    print(std::ranges::is_partitioned(v.crbegin(), v.crend(), is_even));
}

# See also