stable_partition() Algorithm in C++
Posted by Superadmin on August 10 2022 05:36:50

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