Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
c++

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

Vinisha Maheshwari

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.

Library

This function is present in the algorithm library and can be included as:

#include <algorithm>

Syntax

template <class ForwardIterator, class UnaryPredicate> ForwardIterator partition (ForwardIterator first, ForwardIterator last, UnaryPredicate pred);

Parameter

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.

Return value

  • The function returns an iterator that points to the first element of the group of elements that does not satisfy the pred function in the argument, i.e., the range of elements that return false to the predicate.

Code

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;
}
Using partition() function in C++

Explanation

  • In lines 1 and 2, we import the required libraries.
  • In lines 4 to 6, we define a function to check whether the element in the range is multiple of 3 or not.
  • In line 8, we make a main function.
  • In line 10, we initialize an array.
  • In line 12, we use the partition() function to partition the elements that are not multiples of 3 and elements that are multiples of 3.
  • In line 13, we print the first element that the return value of the function points to which does not satisfy the predicate.
  • In line 14, we use a loop to access and display the elements of the partitioned array after using the partition() function on the array.

In this way, we can use the partition() function to partition the elements of a container in C++.

RELATED TAGS

communitycreator
c++
RELATED COURSES

View all Courses

Keep Exploring