How to use the partition_copy() function in C++
In this shot, we will discuss how to use the partition_copy() function in C++. It is present in the partition_copy() function is used to copy elements and then partition them into different locations. If the elements return true, then they are assigned to one location and if they return false the elements are assigned to another location.
Syntax
partition_copy (Input beign, Input end, Output1 begin1, Output2 begin2, UnaryPredicate pred);
Parameter
The partition_copy() function takes the parameters below:
- Begin: Beginning position of existing container.
- End: Ending position of existing container.
- Begin1: Beginning position of new container in which partitioned elements will be copied from the existing container.
- Begin2: Beginning position of the new container in which the rest of the partitioned elements will be copied from the existing container.
- Pred: A user defined function which defines the condition on the basis of which the element partitioning is performed.
Return value
- The
partition_copy()function doesn’t return anything.
Code
Let’s look at the code below.
#include<iostream>#include<algorithm>#include<vector>using namespace std;bool mul3(int x){return (x % 3);}int main(){vector<int> vect = { 12, 15, 9, 7, 84, 74 };vector<int> vec1;vector<int> vec2;int x = count_if (vect.begin(), vect.end(), mul3);vec1.resize(x);vec2.resize(vect.size()-x);partition_copy(vect.begin(), vect.end(), vec1.begin(),vec2.begin(), mul3);cout << "The elements that return true for condition i.e., function are : ";for (int &x : vec1)cout << x << " ";cout << endl;cout << "The elements that return false for condition i.e., function are : ";for (int &x : vec2)cout << x << " ";cout << endl;return 0;}
Explanation
-
In lines 1 to 3, we import the required libraries.
-
In lines 5 to 7, we define a function to check whether the element in the range is a multiple of 3.
-
In line 10, we make a
mainfunction. -
In line 12, we initialize a
vector. -
In lines 14 and 15, we declare 2 vectors to store the 2 partitions of the partitioned vector.
-
In line 17, we use
count_if()function to determine the size of 1 partition to resize the vectors accordingly. -
In lines 18 and 19, we resize both the vectors where the partitions need to get stored.
-
In line 21, we use the
partition_copy()function to store both the partitions of the partitioned vector. -
In lines 23 to 25, we display the first partition which satisfies the condition.
-
In lines 27 to 29, we display the other partition which doesn’t satisfy the condition.
In this way, we can use the partition_copy() function in C++.