C++ std::stable_partition with std::vector














































C++ std::stable_partition with std::vector



 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. 

Program:
 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<iostream>
#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)
{
int count=0,i;

for(i=2;i<=sqrt(a);i++)
if(a%i==0)
count++;

return (count==0);
}

int main()
{
// vector to store all the elements
vector <int> v;
int num,i,n;

cout<<"Enter the number of elements: ";
cin>>num;

cout<<"Enter the elements: ";
for(i=0;i<num;i++)
{
cin>>n;
v.push_back(n);
}

auto it = stable_partition(v.begin(), v.end(), prime);

cout<<"Prime numnbers: "<<endl;
for(auto i=v.begin(); i!=it; i++)
cout<<*i<<" ";

cout<<endl<<"Composite numnbers: "<<endl;
for(auto i=it; i!=v.end(); i++)
cout<<*i<<" ";

}

Comments