C++ STL list, sort() code example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

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 of a list in ascending order or with respect to some other order relation in C++ programming

To show: How to use the C++ list, sort() to arrange the elements of a list in ascending order or with respect to some other order relation in C++ programming

 

// C++ STL list, sort()

#include <list>

#include <iostream>

using namespace std;

 

int main(void)

{

// list container

list <int> ls1;

// list iterator

list <int>::iterator ls1Iter;

 

// insert/push data into the list

ls1.push_back(31);

ls1.push_back(12);

ls1.push_back(40);

ls1.push_back(15);

ls1.push_back(9);

ls1.push_back(44);

 

// print the data and do some operations

cout<<"Before sorting, ls1 list data: ";

for(ls1Iter = ls1.begin(); ls1Iter != ls1.end(); ls1Iter++)

cout<<" "<<*ls1Iter;

cout<<endl;

cout<<"\nOperation: ls1.sort();"<<endl;

ls1.sort();

cout<<"After sorting, ls1 list data: ";

for(ls1Iter = ls1.begin(); ls1Iter != ls1.end(); ls1Iter++)

cout<<" "<<*ls1Iter;

cout<<endl;

cout<<"\nOperation: ls1.sort(greater<int>());"<<endl;

ls1.sort(greater<int>());

cout<<"Re-sort with 'greater than' operation, ls1 list: ";

for(ls1Iter = ls1.begin(); ls1Iter != ls1.end(); ls1Iter++)

cout<<" "<<*ls1Iter;

cout<<endl;

return 0;

}

 

Output examples:

 

Before sorting, ls1 list data: 31 12 40 15 9 44

Operation: ls1.sort();

After sorting, ls1 list data: 9 12 15 31 40 44

Operation: ls1.sort(greater<int>());

Re-sort with 'greater than' operation, ls1 list: 44 40 31 15 12 9

Press any key to continue . . .

 

 

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