C++ STL algorithm, stable_partition() program example
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional project setting: Set project to be compiled as C++
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)
Other info: none
To do: Using the stable_partition() to classify elements in a range into two disjoint sets, with those elements satisfying a unary predicate preceding those that fail to satisfy it, preserving the relative order of equivalent elements in C++ programming
To show: How to use the C++ algorithm, stable_partition() to classify elements in a range into two disjoint sets, with those elements satisfying a unary predicate preceding those that fail to satisfy it, preserving the relative order of equivalent elements in C++ programming
// C++ STL algorithm, stable_partition()
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
bool greaterthan(int value)
{return value > 5;}
int main(void)
{
// vector containers
vector <int> vec1, vec2;
// vector iterators
vector <int>::iterator Iter1, Iter2, result;
int i, j;
// push data in range
for(i = 0; i <= 10; i++)
vec1.push_back(i);
// push data in range
for(j = 0; j <= 4; j++)
vec1.push_back(3);
// randomly shuffle the data
random_shuffle(vec1.begin(), vec1.end());
cout<<"Randomly shuffle vec1 vector data: ";
for(Iter1 = vec1.begin(); Iter1 != vec1.end(); Iter1++)
cout<<*Iter1<<" ";
cout<<endl;
// partition the range with predicate greater than 5...
result = stable_partition (vec1.begin(), vec1.end(), greaterthan);
cout<<"\nThe partitioned set of elements in vec1 vector is: ";
for(Iter1 = vec1.begin(); Iter1 != vec1.end(); Iter1++)
cout<<*Iter1<<" ";
cout<<endl;
cout<<"\nThe first element in vec1 vector fail to satisfy the npredicate greaterthan() is: "<<*result<<endl;
return 0;
}
Output examples:
Randomly shuffle vec1 vector data: 3 1 9 2 0 3 7 3 4 3 8 5 3 3 10 6
The partitioned set of elements in vec1 vector is: 9 7 8 10 6 3 1 2 0 3 3 4 3 5 3 3
The first element in vec1 vector fail to satisfy the npredicate greaterthan() is: 3
Press any key to continue . . .