Changes the order of the elements so that elements that match a criterion are at the front

You're viewing an older version of this page (#4157). View the current version.

View versions (1)

Definition

The partition() algorithm is defined in the standard header <algorithm> and in the nonstandard backward-compatibility header <algo.h>.

Interface

#include <algorithm>
template < class BidirectionalIterator, class Predicate >
   BidirectionalIterator partition(
      BidirectionalIterator first, 
      BidirectionalIterator last, 
      Predicate comp
   );

Parameters:

ParameterDescription
firstA bidirectional iterator addressing the position of the first element in the range to be partitioned
lastA bidirectional iterator addressing the position one past the final element in the range to be partitioned
compUser-defined predicate function object that defines the condition to be satisfied if an element is to be classified. A predicate takes a single argument and returns true or false

Description

Partition function cuts a range in two parts : all elements in the first part satisfy a predicate and elements in the second part doesn't.

After a call to partition, relative order between elements may be changed.

Return Value

Returns the first element that doesn't satisfy the predicate.

Complexity

The complexity is linear; performs last - first applications of pred and at most (last - first)/2 swaps.

References

Example 1
Problem

This program illustrates the use of the STL partition() algorithm to partition the integer values in a vector of integers into two groups: those that are divisible by 3, and those that are not.

Workings
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

/* Determines if an integer is divisible by 3.
   n contains an integer
   Returns true if n is divisible by 3, and otherwise false. */
bool isDivisibleByThree
(
  int n //in 
)
{
  return (n%3 == 0);
}

int main()
{
  int a[] ={11, 7, 9, 4, 8, 12, 2, 5, 3, 10, 1, 6};
  vector<int> v(a, a+12);
  cout <<"\nHere are the contents of the vector:\n";
  for (vector<int>::size_type i=0; i<v.size(); i++)
    cout <<v.at(i)<<" ";

  vector<int>::iterator p = partition(v.begin(), v.end(), 
                                      isDivisibleByThree);
  cout <<"\nAnd here are the contents of the partitioned vector:\n";
  for (vector<int>::size_type i=0; i<v.size(); i++)
    cout <<v.at(i)<<" ";

  cout <<"\nThe iterator p returned by the algorithm points to ";
  if (p == v.end())
    cout <<"\nthe end of the ouput container.";
  else
    cout <<"the value "<<*p<<".";

  return 0;
}
Solution

Output:

Here are the contents of the vector:
11 7 9 4 8 12 2 5 3 10 1 6

And here are the contents of the partitioned vector:
6 3 9 12 8 4 2 5 7 10 1 11

The iterator p returned by the algorithm points to the value 8.

See Also