stable_partition() Algorithm in C++

This C++ program rearranges the container elements using stable_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. The relative order of the elements is preserved.

Here is the source code of the C++ program which rearranges the container elements using stable_partition() algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to rearrange container elements using stable_partition() algorithm
  3.  */
  4. #include <iostream>
  5. #include <vector>
  6. #include <algorithm>
  7. using namespace std;
  8.  
  9. bool isGreaterThanFive(int i)
  10. {
  11.     return i > 5;
  12. }
  13.  
  14. int main() {
  15.     vector<int> v = {5, 1, 6, 2, 4, 3, 9, 8, 10, 7};
  16.     vector<int>::iterator it;
  17.  
  18.     cout << "Vector : ";
  19.     for(vector<int>::iterator i = v.begin(); i != v.end(); i++)
  20.         cout << *i << " ";
  21.     cout << "\n";
  22.  
  23.     it = stable_partition(v.begin(), v.end(), isGreaterThanFive);
  24.     cout << "Elements greater than 5 : ";
  25.     for(vector<int>::iterator i = v.begin(); i != it; i++)
  26.         cout << *i << " ";
  27.     cout << "\n";
  28.  
  29.     cout << "Elements less than or equal to 5 : ";
  30.     for(vector<int>::iterator i = it; i != v.end(); i++)
  31.         cout << *i << " ";
  32.     cout << "\n";
  33. }

$ gcc test.cpp
$ a.out
Vector : 5 1 6 2 4 3 9 8 10 7 
Elements greater than 5 : 6 9 8 10 7 
Elements less than or equal to 5 : 5 1 2 4 3

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.