C++ std::partition with std::vector














































C++ std::partition with std::vector



 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. 

Program:
 Enter some values in a vector and determine which are prime nos. and which are composite
 nos.

#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 = 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