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
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification 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
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.