C++ STL algorithm, sort() program example

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

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 C++ sort() to arrange the elements in a specified range into a non-descending order or according to an ordering criterion specified by a binary predicate in C++ programming

To show: How to use the C++ algorithm, sort() to arrange the elements in a specified range into a non-descending order or according to an ordering criterion specified by a binary predicate in C++ programming

// C++ STL algorithm, sort()

#include <vector>

#include <algorithm>

// for greater<int>()

#include <functional>

#include <iostream>

using namespace std;

// return whether first element is greater than the second

bool UDgreater(int elem1, int elem2)

{

return elem1 > elem2;

}

int main(void)

{

// vector container

vector <int> v1;

// iterator

vector <int>::iterator Iter1;

int i, j;

// push data in range

for (i = 0; i <= 5; i++)

{

v1.push_back(2 * i);

}

for (j = 0; j <= 5; j++)

{

v1.push_back(2 * j + 1);

}

// print the data

cout<<"Original v1 vector is: ";

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

cout<<*Iter1<<" ";

cout<<endl;

// do the sorting

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

cout<<"\nSorted v1 vector is: ";

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

cout<<*Iter1<<" ";

cout<<endl;

// to sort in descending order. specify binary predicate

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

cout<<"\nRe-sorted (greater than) v1 vector is: ";

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

cout<<*Iter1<<" ";

cout<<endl;

// a user-defined (UDgreater()) binary predicate can also be used

sort(v1.begin(), v1.end(), UDgreater);

cout<<"\nRe-sorted (user defined greater than) v1 vector: ";

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

cout<<*Iter1<<" ";

cout<<endl;

return 0;

}

Output examples:

Original v1 vector is: 0 2 4 6 8 10 1 3 5 7 9 11

Sorted v1 vector is: 0 1 2 3 4 5 6 7 8 9 10 11

Re-sorted (greater than) v1 vector is: 11 10 9 8 7 6 5 4 3 2 1 0

Re-sorted (user defined greater than) v1 vector: 11 10 9 8 7 6 5 4 3 2 1 0

Press any key to continue . . .