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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

1 2 3 4 5
filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

Geeksforgeeks This is

Time Complexity : O(nlogn)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.