This article is about the partition() algorithm function with std::vector container. It is
an STL algorithm in <algorithm> header file.
partition() can take two forms:
(1)C++98 template <class BidirectionalIterator, class UnaryPredicate>
BidirectionalIterator partition (BidirectionalIterator first,
BidirectionalIterator last, UnaryPredicate pred);
(2)C++11 template <class ForwardIterator, class UnaryPredicate>
ForwardIterator partition (ForwardIterator first,
ForwardIterator last, UnaryPredicate pred);
Here the range used is [first, last). The first positioned element is included whereas the
last positioned element is not used. It rearranges the elements in the range in such a
way that the elements satisfying a particular condition preceds the elements which doesn't
satisfy the condition. The relative ordering of the elements are not sure to be preserved.
So if we want that then we have to prefer stable_partition. Elements are compared and then
swapped according to the pred function.
pred function accepts an element is the range and returns a value convertible to bool. It
specifies whether the element is to be kept in the front or back.
Return value: An iterator is returned which points to the first element of the second group
of elements(for which the pred value returns false) or last if this group if empty.
Enter some values in a vector and determine which are prime nos. and which are composite
#include<algorithm> // for partition
#include<vector> // for vector
#include<cmath> // for sqrt
using namespace std;
// to check if a given number is prime or not
bool prime(int a)
// vector to store all the elements
vector <int> v;
cout<<"Enter the number of elements: ";
cout<<"Enter the elements: ";
auto it = partition(v.begin(), v.end(), prime);
cout<<"Prime numnbers: "<<endl;
for(auto i=v.begin(); i!=it; i++)
cout<<endl<<"Composite numnbers: "<<endl;
for(auto i=it; i!=v.end(); i++)