In this shot, we will discuss how to use the partition()
function in C++.
This function is used to partition the elements on the basis of the user-defined function (a predicate) passed as an argument.
This function is present in the algorithm
library and can be included as:
#include <algorithm>
template <class ForwardIterator, class UnaryPredicate> ForwardIterator partition (ForwardIterator first, ForwardIterator last, UnaryPredicate pred);
The partition()
function takes the following parameters:
first
: A bidirectional iterator pointing to the first element in the range.last
: A bidirectional iterator pointing to the last element in the range.pred
: A user-defined function that defines the condition on the basis of which the elements are partitioned.pred
function in the argument, i.e., the range of elements that return false
to the predicate.Let’s look at the below code snippet to better understand this.
#include <iostream>#include <algorithm>using namespace std;bool mul3(int x){return (x % 3);}int main(){int arr[] = { 3, 21, 110, 15, 32, 65, 34, 57 };int *pt = partition(arr, arr + 8, mul3);cout << "the first element in the second half is: " << *pt << endl;for (int i = 0; i < 8; i++){cout << arr[i] << " ";}return 0;}
main
function.partition()
function to partition the elements that are not multiples of 3 and elements that are multiples of 3.partition()
function on the array.In this way, we can use the partition()
function to partition the elements of a container in C++.