This C++ program rearranges the container elements using partition() algorithm. The algorithm rearranges the elements of the container such that the elements for which predicate returns true precede the elements for which the predicate returns false. Unlike stable_partition(), the relative order of the elements is not preserved.
Here is the source code of the C++ program which rearranges the container elements using partition() algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to rearrange container elements using partition() algorithm
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool isGreaterThanFive(int i)
{
return i > 5;
}
int main() {
vector<int> v = {5, 1, 6, 2, 4, 3, 9, 8, 10, 7};
vector<int>::iterator it;
cout << "Vector : ";
for(vector<int>::iterator i = v.begin(); i != v.end(); i++)
cout << *i << " ";
cout << "\n";
it = partition(v.begin(), v.end(), isGreaterThanFive);
cout << "Elements greater than 5 : ";
for(vector<int>::iterator i = v.begin(); i != it; i++)
cout << *i << " ";
cout << "\n";
cout << "Elements less than or equal to 5 : ";
for(vector<int>::iterator i = it; i != v.end(); i++)
cout << *i << " ";
cout << "\n";
}
$ gcc test.cpp $ a.out Vector : 5 1 6 2 4 3 9 8 10 7 Elements greater than 5 : 7 10 6 8 9 Elements less than or equal to 5 : 3 4 2 1 5
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
If you find any mistake above, kindly email to [email protected]Related Posts:
- Check C++ Books
- Check Programming Books
- Practice Computer Science MCQs
- Apply for C++ Internship
- Check Computer Science Books