partition(), stable_partition()
partition() reorders the elements based on the true/false evaluation of a unary operation. All the elements that evaluate as true are placed before the elements that evaluate as false. For example, given the sequence {0,1,2,3,4,5,6} and a predicate that tests for elements that are even, the true and false element ranges are {0,2,4,6} and {1,3,5}. Although all the even elements are guaranteed to be placed before any of the odd elements, the relative position of the elements within the reordering is not guaranteed to be preserved. stable_partition() guarantees to preserve the relative order of the elements within the container.
#include <algorithm>
class even_elem {
public:
bool operator()( int elem )
{ return elem%2 ? false : true; }
};
int ia[] = { 29,23,20,22,17,15,26,51,19,12,35,40 };
vector<int> vec( ia, ia+12 );
// partition based on whether element is even:
// 40 12 20 22 26 15 17 51 19 23 35 29
stable_partition( vec.begin(), vec.end(), even_elem() );
|