stable_partition() rearranges elements in a container so that those satisfying a given condition come first, while preserving their original order.
- It’s called stable because it keeps the relative order of elements the same within each group.
- It divides elements in a container (like an array or vector) into two groups based on a given condition .
- The syntax of std::stable_sort is std::stable_sort(first, last, comp), where first and last specify the range of elements to be sorted, and comp is an optional comparison function that determines the sorting order.
- It is present in <algorithm> header file.
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v{6, 9, 0, 1, 2, 7, 5, 8, 0};
stable_partition(v.begin(), v.end(), [](int n) { return n > 0; });
for (int n : v)
{
cout << n << ' ';
}
cout << '\n';
}
Output
6 9 1 2 7 5 8 0 0
#include <algorithm> // For stable_partition
#include <iostream>
#include <vector>
using namespace std;
bool odd(int i)
{
return (i % 2) == 1;
}
int main()
{
vector<int> vct;
// Fill vector with numbers 1 to 9
for (int i = 1; i < 10; ++i)
vct.push_back(i); // 1 2 3 4 5 6 7 8 9
// Rearrange elements so that odd numbers come first
auto bound = stable_partition(vct.begin(), vct.end(), odd);
cout << "Odd numbers:";
for (auto it = vct.begin(); it != bound; ++it)
cout << ' ' << *it;
cout << '\n';
cout << "Even numbers:";
for (auto it = bound; it != vct.end(); ++it)
cout << ' ' << *it;
cout << '\n';
return 0;
}
Output:
odd numbers: 1 3 5 7 9
even numbers: 2 4 6 8