Skip to content
Related Articles

Related Articles

Improve Article
std::forward_list::sort() in C++ STL
  • Last Updated : 26 Jul, 2018

Forward list in STL implements singly linked list. Introduced from C++11, forward list are useful than other containers in insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements.It differs from list by the fact that forward list keeps track of location of only next element while list keeps track to both next and previous elements.

forward_list::sort()

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

Syntax :

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

Examples:

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

Input  : myflist{"This","is","Geeksforgeeks"};
         myflist.sort();
Output : Geekforgeeks, This, is

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 <forward_list>
using namespace std;
  
int main()
{
    // forward list declaration of integer type
    forward_list<int> myflist{1, 5, 3, 2, 4};
      
    // sort function
    myflist.sort();
      
    // printing the forward list after sort
    for (auto it = myflist.begin(); it != myflist.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 <forward_list>
#include <string>
using namespace std;
  
int main()
{
    // forward list declaration of string type
    forward_list<string> myflist{"This","is","Geeksforgeeks"};
      
    // sort function
    myflist.sort();
      
    // printing the forward list after sort
    for (auto it = myflist.begin(); it != myflist.end(); ++it)
        cout << ' ' << *it;
    return 0;
}

Output:

Geeksforgeeks This is

Time Complexity : O(nlogn)

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 :