how to sort a vector in reverse c++
To sort a vector in reverse order in C++, you can use the sort()
function from the <algorithm>
library along with the greater
comparator. Here are the steps to do it:
- Include the necessary libraries:
#include <algorithm>
#include <vector>
- Create a vector and populate it with elements:
std::vector<int> myVector = {5, 2, 8, 1, 10};
- Sort the vector in reverse order using the
sort()
function with thegreater
comparator:
std::sort(myVector.begin(), myVector.end(), std::greater<int>());
- The
std::sort()
function takes three arguments: the beginning iterator of the vector (myVector.begin()
), the ending iterator of the vector (myVector.end()
), and the comparator function (std::greater<int>()
). The
std::greater<int>()
is a predefined comparator function that compares two elements in reverse order.After sorting, the vector
myVector
will be in reverse order:
// Output: 10 8 5 2 1
Here's the complete code snippet:
#include <algorithm>
#include <vector>
int main() {
std::vector<int> myVector = {5, 2, 8, 1, 10};
std::sort(myVector.begin(), myVector.end(), std::greater<int>());
// Print the sorted vector
for (const auto& element : myVector) {
std::cout << element << " ";
}
return 0;
}
This code will output: 10 8 5 2 1
, which is the sorted vector in reverse order.