C++ Standard Library C++ STL Library

C++ <list> - sort() Function



The C++ list::sort function is used to sort the elements of the list container. The comparison produces a strict weak ordering of the elements.

Syntax

//version 1
void sort();
 
//version 2
template <class Compare>
void sort (Compare comp);
//version 1
void sort();
 
//version 2
template <class Compare>
void sort (Compare comp);

Parameters

comp Specify a binary predicate that takes two elements of the list as arguments and returns a bool. It follows the strict weak ordering to order the elements.

Return Value

None.

Time Complexity

Linearithmic i.e, Θ(nlog(n)).

Example:

In the example below, the list::sort function is used to sort the elements of the given list called MyList.

#include <iostream>
#include <list>
using namespace std;
 
int main (){
  list<int> MyList{33, 7, 45, -12, 25, 75};
  list<int>::iterator it;

  cout<<"MyList contains: ";
  for(it = MyList.begin(); it != MyList.end(); it++)
    cout<<*it<<" ";

  //sort elements of the list
  MyList.sort();
  
  cout<<"\nMyList contains: ";
  for(it = MyList.begin(); it != MyList.end(); it++)
    cout<<*it<<" ";

  return 0;
}

The output of the above code will be:

MyList contains: 33 7 45 -12 25 75 
MyList contains: -12 7 25 33 45 75 

Example:

Here, the list is sorted by following: 1) alphabetically and 2) according to the length of the element. Consider the example below:

#include <iostream>
#include <list>
using namespace std;
 
bool compare_length (string s1, string s2) {
  return ( s1.length() < s2.length() );
}

int main () {
  list<string> MyList{"Jo", "John", "Marry", "Kim", "Chandan"};
  list<string>::iterator it;

  cout<<"MyList contains: ";
  for(it = MyList.begin(); it != MyList.end(); it++)
    cout<<*it<<" ";

  //sort elements of the list alphabetically
  MyList.sort();
  
  cout<<"\nMyList contains: ";
  for(it = MyList.begin(); it != MyList.end(); it++)
    cout<<*it<<" ";

  //sort elements of the list according 
  //to length of the element
  MyList.sort(compare_length);
  
  cout<<"\nMyList contains: ";
  for(it = MyList.begin(); it != MyList.end(); it++)
    cout<<*it<<" ";

  return 0;
}

The output of the above code will be:

MyList contains: Jo John Marry Kim Chandan 
MyList contains: Chandan Jo John Kim Marry 
MyList contains: Jo Kim John Marry Chandan 

❮ C++ <list> Library