std::partition_copy

From Cppreference

Jump to: navigation, search
Defined in header <algorithm>

template< class InputIterator, class OutputIterator1,

          class OutputIterator2, class UnaryPredicate >
std::pair<OutputIterator1, OutputIterator2>
     partition_copy(InputIterator first, InputIterator last,
                    OutputIterator1 d_first_true, OutputIterator2 d_first_false,

                    UnaryPredicate p);
(C++11 feature)

Copies the elements that satisfy the predicate p from the range [first, last) to the range beginning at d_first_true, and copies the elements that do not satisfy p to the range beginning at d_first_false.

Contents

[edit] Parameters

first, last - the range of elements to sort
d_first_true - the beginning of the output range for the elements that satisfy p
d_first_false - the beginning of the output range for the elements that do not satisfy p
p - unary predicate which returns ​true if the element should be placed in d_first_true.

The signature of the predicate function should be equivalent to the following:

bool pred(const Type &a);

The signature does not need to have const &, but the function must not modify the objects passed to it.
The type Type must be such that an object of type InputIterator can be dereferenced and then implicitly converted to Type. ​

[edit] Return value

A pair constructed from the iterator to the end of the d_first_true range and the iterator to the end of the d_first_false range.

[edit] Complexity

Exactly distance(first, last) applications of p.

[edit] Equivalent function

[edit] Example

#include <iostream>
#include <algorithm>
#include <utility>
using namespace std;
 
int main()
{
	int arr [10] = {1,2,3,4,5,6,7,8,9,10};
	int true_arr [5] = {0};
	int false_arr [5] = {0};
 
	partition_copy(std::begin(arr), std::end(arr), std::begin(true_arr),std::begin(false_arr),
		[] (int i) {return i > 5;});
 
	cout << "true_arr: ";
	for (auto it = std::begin(true_arr); it != std::end(true_arr); ++it)
		cout << *it << ' ';
	cout << '\n'; 
 
	cout << "false_arr: ";
	for (auto it = std::begin(false_arr); it != std::end(false_arr); ++it)
		cout << *it << ' ';
	cout << '\n'; 
 
	return 0;
 
}

Output:

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

[edit] See also

partition
divides a range of elements into two groups
(function template)
stable_partition
divides elements into two groups while preserving their relative order
(function template)