sort vector in descending order c++ code example

Example 1: how to sort a vector in reverse c++

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
   vector<int> v = { 10, 9, 8, 6, 7, 2, 5, 1 };
   sort(v.begin(), v.end(), greater <>());
}

Example 2: how to sort in descending order c++

int arr[10];
int length = sizeof(arr)/sizeof(arr[0]); 
sort(arr, arr+length, greater<int>());

Example 3: sort vector struct c++

struct data{
    string word;
    int number;
};


bool my_cmp(const data& a, const data& b)
{
    // smallest comes first
    return a.number < b.number;
}

std::sort(A.begin(), A.end(), my_cmp);

Example 4: sort vector descending

int main() 
{ 
    // Get the vector 
    vector<int> a = { 1, 45, 54, 71, 76, 12 }; 
  
    // Print the vector 
    cout << "Vector: "; 
    for (int i = 0; i < a.size(); i++) 
        cout << a[i] << " "; 
    cout << endl; 
  
    // Sort the vector in descending order 
    sort(a.begin(), a.end(), greater<int>()); 
  
    // Print the reversed vector 
    cout << "Sorted Vector in descendiing order:n"; 
    for (int i = 0; i < a.size(); i++) 
        cout << a[i] << " "; 
    cout << endl; 
  
    return 0; 
}

Example 5: sort vector in descending order

sort(a.begin(), a.end(), greater<int>());

Tags:

Java Example