How to use the partition_point() function in C++

The partition_point() function in C++ is present in the <algorithm> library. It is used to obtain the partition point after using the partition() function on a container.

Parameters

partition_point() takes the following parameters:

  • Begin: A bidirectional iterator pointing to the first element in the range.
  • End: 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 partitioning of the elements is performed.

Return value

  • The partition_point() function returns an iterator that points to the partition point i.e. the first element of the partitioned range which doesn’t satisfy the Pred function in the argument.

Code

Let us 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 };
partition(vect.begin(), vect.end(), mul3);
cout << "The partitioned vector is : ";
for (int &x : vect)
cout << x << " ";
cout << endl;
vector<int>::iterator i;
auto it = partition_point(vect.begin(), vect.end(), mul3);
cout << "The partition which satisfies the condition is: ";
for ( i= vect.begin(); i!=it; i++)
cout << *i << " ";
cout << endl;
}

Explanation

  • In lines 1 to 3, we imported the required libraries.

  • In lines 5 to 7, we defined a function to check whether the element in the range is multiple of three or not.

  • In line 9, we made a main function.

  • In line 10, we initialized a vector.

  • In line 12, we used the partition() function to partition the elements which are not multiples of three and elements that are multiples of three.

  • In lines 14 and 15, we used a loop to access and display the elements of the partitioned vector after using the partition() function on the vector.

  • In line 18, we declared an iterator to a vector.

  • In line 19, we used partition_point() to access the partition point

  • In lines 21 to 22, we displayed the partition which satisfies the condition.

Free Resources