std::partition
From cppreference.com
| Defined in header <algorithm>
|
||
| (1) | ||
| template< class BidirIt, class UnaryPredicate > BidirIt partition( BidirIt first, BidirIt last, UnaryPredicate p ); |
(until C++11) | |
| template< class ForwardIt, class UnaryPredicate > ForwardIt partition( ForwardIt first, ForwardIt last, UnaryPredicate p ); |
(since C++11) | |
| template< class ExecutionPolicy, class ForwardIt, class UnaryPredicate > ForwardIt partition( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, UnaryPredicate p ); |
(2) | (since C++17) |
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 not preserved. 2) Same as (1), but executed according to
policy. This overload does not participate in overload resolution unless std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> is trueParameters
| first, last | - | the range of elements to reorder |
| policy | - | the execution policy to use. See execution policy for details. |
| p | - | unary predicate which returns true if the element should be ordered before other elements. The signature of the predicate function should be equivalent to the following: bool pred(const Type &a); The signature does not need to have const &, but the function must not modify the objects passed to it. |
| Type requirements | ||
-BidirIt must meet the requirements of BidirectionalIterator.
| ||
-ForwardIt must meet the requirements of ValueSwappable and ForwardIterator. However, the operation is more efficient if ForwardIt also satisfies the requirements of BidirectionalIterator
| ||
-UnaryPredicate must meet the requirements of Predicate.
| ||
Return value
Iterator to the first element of the second group.
Complexity
Given N = std::distance(first,last),
1) Exactly N applications of the predicate. At most N/2 swaps if
ForwardIt meets the requirements of BidirectionalIterator, and at most N swaps otherwise.2)
O(N log N) swaps and O(N) applications of the predicate.Exceptions
The overload with a template parameter named ExecutionPolicy reports errors as follows:
- If execution of a function invoked as part of the algorithm throws an exception and
ExecutionPolicyis one of the three standard policies, std::terminate is called. For any otherExecutionPolicy, the behavior is implementation-defined. - If the algorithm fails to allocate memory, std::bad_alloc is thrown.
Possible implementation
template<class ForwardIt, class UnaryPredicate> ForwardIt partition(ForwardIt first, ForwardIt last, UnaryPredicate p) { first = std::find_if_not(first, last, p); if (first == last) return first; for(ForwardIt i = std::next(first); i != last; ++i){ if(p(*i)){ std::iter_swap(i, first); ++first; } } return first; } |