To sort a vector in descending order in C++, you can use the sort
function from the <algorithm>
header with a custom comparison function.
In this example,
<iostream>
and <vector>
.vec
containing several numeric values.sort
function, passing a custom comparison function that sorts elements in descending order. This function sorts the elements of the vector in descending order.for
loop.#include <iostream>
#include <vector>
#include <algorithm>
int main() {
// Step 1: Create a vector
std::vector<int> vec = {5, 2, 8, 3, 9, 1};
// Step 2: Sort the vector in descending order
std::sort(vec.begin(), vec.end(), std::greater<int>());
// Step 3: Print the sorted vector
std::cout << "Sorted vector: ";
for (int num : vec) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
Sorted vector: 9 8 5 3 2 1
In this example,
<iostream>
and <vector>
.vec
containing several string values.sort
function, passing a custom comparison function that sorts elements in descending order based on lexicographic order. This function sorts the elements of the vector in descending order.for
loop.#include <iostream>
#include <vector>
#include <algorithm>
int main() {
// Step 1: Create a vector
std::vector<std::string> vec = {"apple", "banana", "orange", "grape", "kiwi"};
// Step 2: Sort the vector in descending order
std::sort(vec.begin(), vec.end(), std::greater<std::string>());
// Step 3: Print the sorted vector
std::cout << "Sorted vector: ";
for (const std::string& str : vec) {
std::cout << str << " ";
}
std::cout << std::endl;
return 0;
}
Sorted vector: orange kiwi grape banana apple
In this tutorial, we learned How to Sort a Vector in Descending Order in C++ language with well detailed examples.