Javatpoint Logo
Javatpoint Logo

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.



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 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.


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():


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:


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:


3 2 4 5 7 0 0 0 0

Example 4

Let's see another simple example:



Next TopicC++ Algorithm

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA