std::forward_list::sort() in C++ STL
Last Updated :
18 Aug, 2021
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 :
1. forwardlistname.sort()
Parameters :
No parameters are passed.
Result :
The elements of the container
are sorted in ascending order.
2. forwardlistname.sort(predicate)
Parameters :
predicate is used to define your own custom sorting function,
it will return boolean output
Result :
The elements of the container
sorted in the order as per predicate function
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.
CPP
#include <iostream>
#include <forward_list>
using namespace std;
int main()
{
forward_list< int > myflist{1, 5, 3, 2, 4};
myflist.sort();
for ( auto it = myflist.begin(); it != myflist.end(); ++it)
cout << ' ' << *it;
return 0;
}
|
Output:
1 2 3 4 5
CPP
#include <iostream>
#include <forward_list>
#include <string>
using namespace std;
int main()
{
forward_list<string> myflist{ "This" , "is" , "Geeksforgeeks" };
myflist.sort();
for ( auto it = myflist.begin(); it != myflist.end(); ++it)
cout << ' ' << *it;
return 0;
}
|
Output:
Geeksforgeeks This is
Time Complexity : O(nlogn)
C++
#include <iostream>
#include <forward_list>
#include <string>
using namespace std;
bool comparator(string a, string b) {
return a.length() <= b.length();
}
int main()
{
forward_list<string> myflist{ "This" , "is" , "Geeksforgeeks" };
myflist.sort(comparator);
for ( auto it = myflist.begin(); it != myflist.end(); ++it)
cout << ' ' << *it;
return 0;
}
|
Output :
is This Geeksforgeeks
Time Complexity – O(nlog(n))
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...