std::forward_list::sort() in C++ STL

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)

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

Article Tags :
C++
Practice Tags :