C++ Algorithm partition_copy()

C++ Algorithm partition_copy() function is used to copy the elements for which a condition is true to one destination, and false to another. The elements must belong to a specified range.

Syntax

Parameter

first: An input iterator pointing to the first element in the range to check for a condition.

last: An input iterator pointing to the past last element of the range.

pred: A user-defined unary predicate function that defines the condition to be tested.

result_true: An output iterator used to copy elements for which pred returns true.

result_false: An output iterator used to copy elements for which pred returns false.

Return value

This function returns a pair of iterators with the end of generated sequences addressed by result_true and result_false, respectively.

Complexity

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

Data races

The object in the range [first, last) are accessed where the each element is accessed exactly once.

Exceptions

This function throws an exception if any of pred, an element's assignment or an operation on iterator throws an exception.

Note: The invalid parameters cause an undefined behavior.

Example 1

Let's see the simple example to demonstrate the use of partition_copy():

Output:

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

Example 2

Let's see another simple example:

Output:

true_arr: 6 7 8 9 10 
false_arr: 1 2 3 4 5

Example 3

Let's see another simple example:

Output:

v : 1,2,3,4,5,
evens : 2,4,
odds  : 1,3,5,

Example 4

Let's see another simple example:

Output:

Evens : 4
Odds  : 5

Contents of the vector is : 
[0] : 2
[1] : 4
[2] : 6
[3] : 8

Contents of the vector is : 
[0] : 1
[1] : 3
[2] : 5
[3] : 7
[4] : 9

Next TopicC++ Algorithm




Latest Courses