sort in descending order c++ stl
To sort elements in descending order using the C++ STL, you can follow these steps:
Include the necessary header file:
cpp #include <algorithm>
Create a container with the elements you want to sort. For this example, let's assume we have a vector of integers named
myVector
:cpp std::vector<int> myVector;
Populate the container with the elements you want to sort. You can add elements to the vector using the
push_back()
function:cpp myVector.push_back(5); myVector.push_back(2); myVector.push_back(8); myVector.push_back(1);
Use the
sort()
function from the<algorithm>
header to sort the elements in descending order. Pass the beginning and end iterators of the container, along with a lambda function as the third argument to specify the sorting order:cpp std::sort(myVector.begin(), myVector.end(), [](int a, int b){ return a > b; });
In this example, the lambda function [](int a, int b){ return a > b; }
is used to define the sorting order. It compares two integers a
and b
and returns true
if a
is greater than b
, indicating that a
should come before b
in the sorted sequence.
- After executing the
sort()
function, the elements inmyVector
will be sorted in descending order.
Here's the complete code:
#include <algorithm>
#include <vector>
int main() {
std::vector<int> myVector;
myVector.push_back(5);
myVector.push_back(2);
myVector.push_back(8);
myVector.push_back(1);
std::sort(myVector.begin(), myVector.end(), [](int a, int b){ return a > b; });
// Print the sorted vector
for (int num : myVector) {
std::cout << num << " ";
}
return 0;
}
When you run this code, it will output: 8 5 2 1
, which is the sorted vector in descending order.