how to sort in descending order in c++

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    std::vector<int> numbers = {5, 2, 9, 1, 5, 6};

    std::sort(numbers.begin(), numbers.end(), std::greater<int>());

    std::cout << "Numbers sorted in descending order: ";
    for (const auto &num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}
  1. #include <iostream>: Includes the input/output stream library to perform input and output operations.

  2. #include <algorithm>: Includes the algorithm library containing functions to work with ranges of elements, including sorting.

  3. #include <vector>: Includes the vector library for using the vector container.

  4. std::vector<int> numbers = {5, 2, 9, 1, 5, 6};: Declares a vector named numbers and initializes it with some integer values.

  5. std::sort(numbers.begin(), numbers.end(), std::greater<int>());: Uses the std::sort function from the algorithm library to sort the elements in numbers vector. The std::greater<int>() function object is used as the comparator to sort the elements in descending order.

  6. std::cout << "Numbers sorted in descending order: ";: Outputs a message indicating the sorted order will be displayed.

  7. for (const auto &num : numbers) { std::cout << num << " "; }: Iterates through the sorted numbers vector and prints each element to the console separated by a space.

  8. std::cout << std::endl;: Outputs an end-of-line character to start a new line in the console.

  9. return 0;: Indicates successful program execution and returns 0 to the operating system.