To sort an array in descending order in C++, you can use the `sort` function from the `
In this example,
numbers
.sort
function to sort the vector of integers using the custom comparison function.#include <iostream>
#include <algorithm>
#include <vector>
bool compare_desc(int a, int b) {
return a > b;
}
int main() {
std::vector<int> numbers = {5, 2, 8, 1, 9};
std::sort(numbers.begin(), numbers.end(), compare_desc);
for (int number : numbers) {
std::cout << number << " ";
}
return 0;
}
Sorted array in descending order: 9 8 5 2 1
In this example,
words
.sort
function to sort the vector of strings using the custom comparison function.#include <iostream>
#include <algorithm>
#include <vector>
bool compare_desc(const std::string& a, const std::string& b) {
return a > b;
}
int main() {
std::vector<std::string> words = {"apple", "banana", "cherry", "date"};
std::sort(words.begin(), words.end(), compare_desc);
for (const std::string& word : words) {
std::cout << word << " ";
}
return 0;
}
Sorted array in descending order: date cherry banana apple
In this tutorial, we learned How to Sort an Array in Descending Order in C++ language with well detailed examples.