The sort() Method is used to sort a List in Ascending order.
#include <iostream> #include <list> using namespace std; int main() { list<string> x = {"Mohan", "Kriti", "Salim"}; x.sort(); for (string data : x) { cout << data << endl; } return 0; }
So, in the above code we have created a List and initialised to the variable x.
list<string> x = {"Mohan", "Kriti", "Salim"};
Below is how the values are positioned in the List,
Then we have used the sort() method to sort the List x in ascending order.
x.sort();
And the List x gets sorted with Kriti as the first value, Mohan second and Salim as the third.
And we get the below output.
Even here the sort() Method is used to sort a List with numbers in Increasing/Deceasing Order.
At first let us see an example to sort a List with numbers in Increasing order.
#include <iostream> #include <list> using namespace std; int main() { list<int> x = {5, 3, 2, 4}; x.sort(); for (int data : x) { cout << data << endl; } return 0; }
So, in the above code we have created a List and initialised to the variable x.
list<int> x = {5, 3, 2, 4};
Below is how the values are positioned in the List,
Then we have used the sort() method to sort the List x in increasing order.
x.sort();
And the numbers in the List x gets sorted.
And we get the below output.
Next let us see, how to sort a List in Descending order.
#include <iostream> #include <list> using namespace std; int main() { list<int> x = {5, 3, 2, 4}; x.sort(); x.reverse(); for (int data : x) { cout << data << endl; } return 0; }
So, in the above code we have created a List and initialised to the variable x.
list<int> x = {5, 3, 2, 4};
Below is how the values are positioned in the List,
Then we have used the sort() method to sort the List x in increasing order.
x.sort();
Then we have used the reverse() method to reverse the List
x.reverse();
And the List x gets sorted in decreasing order.
And we get the below output.