std::stable_partition

Header: <algorithm>

  1. Reorders the elements in the range [first,last) in such a way that all elements for which the predicate p returns true precede the elements for which predicate p returns false. Relative order of the elements is preserved.

# Declarations

template< class BidirIt, class UnaryPred >
BidirIt stable_partition( BidirIt first, BidirIt last, UnaryPred p );

(constexpr since C++26)

template< class ExecutionPolicy, class BidirIt, class UnaryPred >
BidirIt stable_partition( ExecutionPolicy&& policy,
BidirIt first, BidirIt last, UnaryPred p );

(since C++17)

# Parameters

# Return value

Iterator to the first element of the second group.

# Notes

This function attempts to allocate a temporary buffer. If the allocation fails, the less efficient algorithm is chosen.

Implementations in libc++ and libstdc++ also accept ranges denoted by LegacyForwardIterators as an extension.

# Example

#include <algorithm>
#include <iostream>
#include <vector>
 
int main()
{
    std::vector<int> v{0, 0, 3, -1, 2, 4, 5, 0, 7};
    std::stable_partition(v.begin(), v.end(), [](int n) { return n > 0; });
    for (int n : v)
        std::cout << n << ' ';
    std::cout << '\n';
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 2150C++98std::stable_partition was only required to place oneelement satisfying p before one element not satisfying pcorrected therequirement

# See also