Skip to content
Related Articles

Related Articles

Improve Article

std::list::sort in C++ STL

  • Difficulty Level : Basic
  • Last Updated : 17 Jan, 2018
Geek Week

Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists.

list::sort()

sort() function is used to sort the elements of the container by changing their positions.

Syntax :

listname.sort()
Parameters :
No parameters are passed.
Result :
The elements of the container
are sorted in ascending order.

Examples:

Input  : mylist{1, 5, 3, 2, 4};
         mylist.sort();
Output : 1, 2, 3, 4, 5

Input  : mylist{"hi", "bye", "thanks"};
         mylist.sort();
Output : bye, hi, thanks

Errors and Exceptions



1. It has a basic no exception throw guarantee.
2. Shows error when a parameter is passed.




// SORTING INTEGERS
// CPP program to illustrate
// Implementation of sort() function
#include <iostream>
#include <list>
using namespace std;
  
int main()
{
    // list declaration of integer type
    list<int> mylist{ 1, 5, 3, 2, 4 };
  
    // sort function
    mylist.sort();
  
    // printing the list after sort
    for (auto it = mylist.begin(); it != mylist.end(); ++it)
        cout << ' ' << *it;
    return 0;
}

Output:

1 2 3 4 5




// SORTING STRINGS
// CPP program to illustrate
// Implementation of sort() function
#include <iostream>
#include <list>
#include <string>
using namespace std;
  
int main()
{
    // list declaration of string type
    list<string> mylist{ "hi", "bye", "thanks" };
  
    // sort function
    mylist.sort();
  
    // printing the list after sort
    for (auto it = mylist.begin(); it != mylist.end(); ++it)
        cout << ' ' << *it;
    return 0;
}

Output:

bye hi thanks

Time Complexity : O(nlogn)

Similar function : Sort in C++ STL

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :