C++ <forward_list> - sort() Function
The C++ forward_list::sort function is used to sort the elements of the forward_list container. The comparison produces a strict weak ordering of the elements.
Syntax
//version 1 void sort(); //version 2 template <class Compare> void sort (Compare comp);
Parameters
comp |
Specify a binary predicate that takes two elements of the forward_list as arguments and returns a bool. It follows the strict weak ordering to order the elements. |
Return Value
None.
Time Complexity
Linearithmic i.e, Θ(nlog(n)).
Example:
In the example below, the forward_list::sort function is used to sort the elements of the given forward_list called flist.
#include <iostream> #include <forward_list> using namespace std; int main (){ forward_list<int> flist{33, 7, 45, -12, 25, 75}; forward_list<int>::iterator it; cout<<"flist contains: "; for(it = flist.begin(); it != flist.end(); it++) cout<<*it<<" "; //sort elements of the forward_list flist.sort(); cout<<"\nflist contains: "; for(it = flist.begin(); it != flist.end(); it++) cout<<*it<<" "; return 0; }
The output of the above code will be:
flist contains: 33 7 45 -12 25 75 flist contains: -12 7 25 33 45 75
Example:
Here, the forward_list is sorted by following: 1) alphabetically and 2) according to the length of the element. Consider the example below:
#include <iostream> #include <forward_list> using namespace std; bool compare_length (string s1, string s2) { return ( s1.length() < s2.length() ); } int main () { forward_list<string> flist{"Jo", "John", "Marry", "Kim", "Chandan"}; forward_list<string>::iterator it; cout<<"flist contains: "; for(it = flist.begin(); it != flist.end(); it++) cout<<*it<<" "; //sort elements of the forward_list alphabetically flist.sort(); cout<<"\nflist contains: "; for(it = flist.begin(); it != flist.end(); it++) cout<<*it<<" "; //sort elements of the forward_list according //to length of the element flist.sort(compare_length); cout<<"\nflist contains: "; for(it = flist.begin(); it != flist.end(); it++) cout<<*it<<" "; return 0; }
The output of the above code will be:
flist contains: Jo John Marry Kim Chandan flist contains: Chandan Jo John Kim Marry flist contains: Jo Kim John Marry Chandan
❮ C++ <forward_list> Library