partition |
Partition a range using a predicate.
Place all elements in the range [
first ... last ) that cause pred
to evaluate to true before all elements in the
range that cause pred to evaluate to false
. Return an iterator positioned at the first element of the second sequence.
#include <algorithm>
template< class BidirectionalIterator, class Predicate >
BidirectionalIterator partition
(
BidirectionalIterator first,
BidirectionalIterator last,
Predicate pred
);
Time complexity is O(N), where
N = ( last - first
), as pred will be evaluated N times and at most N /
2 swaps will be performed.
#include <iostream>
#include <algorithm>
int numbers[ 6 ] = { 6, 12, 3, 10, 1, 20 };
int
less_10( int a_ )
{
return a_ < 10 ? 1 : 0;
}
void
main()
{
partition( numbers, numbers + 6, less_10 );
for ( int i = 0; i < 6; ++i )
cout << numbers[ i ] << ` `;
cout << "\n";
}
6 1 3 10 12 20
#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <functional>
#include <iterator>
#include <vector>
void
main()
{
vector< int > v1( 10 );
for ( int i = 0; i < v1.size(); ++i )
v1[ i ] = rand() % 20;
ostream_iterator< int > iter( cout, " " );
copy( v1.begin(), v1.end(), iter );
cout << "\n";
partition( v1.begin(), v1.end(), bind2nd( less< int >(), 11 ) );
copy( v1.begin(), v1.end(), iter );
cout << "\n";
}
6 10 2 10 16 17 15 15 8 6
6 10 2 10 6 8 15 15 17 16
Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.