C++ STL algorithm, random_shuffle() and 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 C++ 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 in C++ programming

To show: How to use the C++ algorithm, 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 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 userdefgreater(int elem1, int elem2)

{return elem1 > elem2;}

 

int main(void)

{

// container

vector <int> vec1;

// iterator

vector <int>::iterator Iter1;

int k;

 

// push data in range

for(k = 0; k <= 15; k++)

vec1.push_back(k);

 

// print the data

cout<<"vec1 vector data: ";

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

cout<<*Iter1<<" ";

cout<<endl;

// shuffling the data

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

cout<<"\nRandom shuffle vec1 vector data: ";

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

cout<<*Iter1<<" ";

cout<<endl;

// default sorting

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

cout<<"\nSorted 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;

}

 

Output examples:

 

vec1 vector data: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Random shuffle vec1 vector data: 12 1 9 2 0 11 7 3 4 15 8 5 14 13 10 6

Sorted vec1 vector data: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Re-sorted (greater) vec1 vector data: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

User defined re-sorted vec1 vector data:15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

Press any key to continue . . .

 

 

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