This article is about the stable_partition() algorithm function with std::vector container.
It is an STL algorithm in <algorithm> header file.
stable_partition() can take one form:
template <class BidirectionalIterator, class UnaryPredicate>
BidirectionalIterator stable_partition (BidirectionalIterator first,
BidirectionalIterator 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 is sure to be preserved.
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
nos. The numbers should be shown as entered by the user.
#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 = stable_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++)