Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




C++ - SORT LIST ELEMENTS


How to sort a List in Ascending Order?


The sort() Method is used to sort a List in Ascending order.


Example :



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


Output :



  Kriti
  Mohan
  Salim

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,

java_Collections

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.

java_Collections

And we get the below output.

Output :



  Kriti
  Mohan
  Salim

How to sort a List with numbers in Increasing Order?


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.


Example :



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


Output :



  2
  3
  4
  5

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,

java_Collections

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.

java_Collections

And we get the below output.

Output :



  2
  3
  4
  5

Next let us see, how to sort a List in Descending order.


How to sort a List with numbers in Descending Order?


Example :



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


Output :



  5
  4
  3
  2

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,

java_Collections

Then we have used the sort() method to sort the List x in increasing order.


x.sort();
java_Collections


Then we have used the reverse() method to reverse the List


x.reverse();

And the List x gets sorted in decreasing order.

java_Collections

And we get the below output.

Output :



  5
  4
  3
  2