C++ std::partition_copy with std::vector














































C++ std::partition_copy with std::vector



 This article is about the partition_copy() algorithm function with std::vector container. It
 is an STL algorithm in <algorithm> header file.  
 partition_copy() can take only one forms:
    template <class InputIterator, class OutputIterator1,class OutputIterator2,
                                            class UnaryPredicate pred>
pair<OutputIterator1,OutputIterator2> partition_copy (InputIterator first, InputIterator last,
OutputIterator1 result_true, OutputIterator2 result_false, UnaryPredicate pred);
Here the range used is [first, last). The first positioned element is included whereas the last positioned element is not used. It totlly works like the partition function (refer:
 article-C++ std::partition_copy with std::vector) but saves the two ranges in two different
 containers. The values which satisfy the condition are stored in the range pointed by
 result_true and the rest in result_false.

 result_true - Output iterator to the range where the elements satisfy the condition.
 result_false - Output iterator to the range where the elements doesn't satisfy the
                condition.
 
 Return value: A pair of iterators which points to the last elements of the ranges
 result_true and result_false.

 Program:
 Given a range find the odd and even numbers and make the odd numbers even by adding 1 to
 them and vice-versa by subtracting 1 from them.

#include<iostream>
#include<algorithm> // for partition_copy, for_each, count_if
#include<vector> // for vector, begin, end, resize, size

using namespace std;

// to check if a given number is odd or not
bool odd_check(int a)
{
return (a%2==1);
}
// odd to even by adding 1
void odd_to_even(int a)
{
cout<<a+1<<" ";
}
// even to odd by subtracting 1
void even_to_odd(int a)
{
cout<<a-1<<" ";
}

int main()
{
// vector to store all the elements
vector <int> v;
// to store the odd and even numbers separately
vector <int> odd, even;
int num, i, n, odd_count;

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

cout<<"Enter the elements: ";
for(i=0;i<num;i++)
{
cin>>n;
v.push_back(n);
}
// to count number of odd and even numbers
odd_count = count_if(v.begin(), v.end(), odd_check);
odd.resize(odd_count);
even.resize(v.size()-odd_count);

partition_copy(v.begin(), v.end(), odd.begin(), even.begin(), odd_check);

cout<<"Converting Odd to Even: "<<endl;
for_each(odd.begin(), odd.end(), odd_to_even);

cout<<endl<<"Converting Even to Odd: "<<endl;
for_each(even.begin(), even.end(), even_to_odd);
}

Comments