C++ STL algorithm, stable_sort() 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_sort() to sort the elements in a specified range into a non-descending order or according to an ordering criterion specified by a binary predicate and preserves the relative ordering of equivalent elements in C++ programming

To show: Using the C++ algorithm, stable_sort() to sort the elements in a specified range into a non-descending order or according to an ordering criterion specified by a binary predicate and preserves the relative ordering of equivalent elements in C++ programming

 

// C++ STL algorithm, stable_sort(), random_shuffle()

#include <vector>

#include <algorithm>

// for greater<int>()

#include <functional>

#include <iostream>

using namespace std;

 

// return whether first element is greater than the second

bool userdefgreater(int elem1, int elem2)

{ return elem1 > elem2;}

 

int main(void)

{

// vector container

vector <int> vec1;

// vector iterator

vector <int>::iterator Iter1;

// push data into the vector

for (int i=10; i<=20; i++)

vec1.push_back(i);

 

random_shuffle(vec1.begin(), vec1.end());

cout<<"Random shuffle vec1 vector data: ";

for(Iter1 = vec1.begin(); Iter1 != vec1.end(); Iter1++)

cout<<*Iter1<<" ";

cout<<endl;

sort(vec1.begin(), vec1.end());

cout<<"\nDefault sorted vec1 vector data: ";

for(Iter1 = vec1.begin(); Iter1 != vec1.end(); Iter1++)

cout<<*Iter1<<" ";

cout<<endl;

// to sort in descending order, specify binary predicate

sort(vec1.begin(), vec1.end(), greater<int>());

cout<<"\nRe-sorted (greater) vec1 vector data: ";

for(Iter1 = vec1.begin(); Iter1 != vec1.end(); Iter1++)

cout<<*Iter1<<" ";

cout<<endl;

// a user-defined binary predicate can also be used

sort(vec1.begin(), vec1.end(), userdefgreater);

cout<<"\nUser defined re-sorted vec1 vector data: ";

for(Iter1 = vec1.begin(); Iter1 != vec1.end(); Iter1++)

cout<<*Iter1<<" ";

cout<<endl;

return 0;

}

 

 

C and C++ Programming Resources | C & C++ Code Example Index