Home » C++ algorithm stable_partition() function

C++ algorithm stable_partition() function

by Online Tutorials Library

C++ Algorithm stable_partition()

C++ Algorithm stable_partition() function is used to classify the elements in the range [first, last), in such a way that all the elements for which pred returns true precede all those for which it returns false, where the relative order of elements is preserved.

Note: – This function is generally implemented using an internal temporary buffer.

Syntax

Parameter

first: An bidirectional iterator pointing to the first element in the range to be partitioned.

last: An bidirectional iterator pointing to the past last element in the range to be partitioned.

pred: A user-defined unary predicate function that defines the condition to be satisfied if an element is to be classified.

Return value

This function returns an iterator to the first element of the range to not satisfy the predicate condition.

Complexity

Complexity is linear in the range [first, last) if enough memory is available: Applies pred to each element.

Data races

The object in the range [first, last) are modified.

Exceptions

This function throws an exception if any of element’s comparisons, an element swaps or an operation on iterator throws an exception.

Please note that invalid parameters cause an undefined behavior.

Example 1

Let’s see the simple example to demonstrate the use of stable_partition():

Output:

odd elements: 1 3 5 7 9  even elements: 2 4 6 8  

In the above example, elements from 1 to 9 are partitioned into even and odd elements.

Example 2

Let’s see another simple example:

Output:

Vector v1 is ( 4 10 5 5 5 5 5 1 6 9 3 7 8 2 0 5 ).  The partitioned set of elements in v1 is:   ( 10 6 9 7 8 4 5 5 5 5 5 1 3 2 0 5 ).  The first element in v1 to fail to satisfy the   predicate greater5 is: 4.  

Example 3

Let’s see another simple example to quick sort the elements of vector using partition() function:

Output:

3 2 4 5 7 0 0 0 0  

Example 4

Let’s see another simple example:

Output:

0  3  6  12  9  1  4  5  7  

Next TopicC++ Algorithm

You may also like