sort function from bigest to smallest c++
The sort
function in C++ can be used to sort elements in an array or a container in ascending order by default. If you want to sort the elements in descending order (from biggest to smallest), you can provide a custom comparison function or use the greater
function object.
Here's an example of using the sort
function to sort elements in descending order:
#include <iostream>
#include <algorithm>
#include <vector>
bool compare(int a, int b) {
return a > b; // Sort in descending order
}
int main() {
std::vector<int> numbers = {5, 2, 8, 3, 1};
std::sort(numbers.begin(), numbers.end(), compare);
for (int num : numbers) {
std::cout << num << " ";
}
return 0;
}
In this example, we have a vector numbers
with elements {5, 2, 8, 3, 1}
. We define a custom comparison function compare
that returns true
if the first argument is greater than the second argument. This ensures that the sort
function arranges the elements in descending order.
The sort
function is called with three arguments: the beginning and end iterators of the container (numbers.begin()
and numbers.end()
), and the comparison function (compare
). The sort
function rearranges the elements in the vector, placing them in descending order.
Finally, we iterate over the sorted vector and print the elements to the console, resulting in the output: 8 5 3 2 1
.
By using a custom comparison function, the sort
function can be used to sort elements in a container in any desired order.