- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sorting a vector in descending order in C++
Sorting a vector in C++ can be done by using std::sort(). It is defined in<algorithm> header. To get a stable sort std::stable_sort is used. It is exactly like sort() but maintain the relative order of equal elements. Quicksort(), mergesort() can also be used, as per requirement.
Sorting a vector in descending order can be done by using std::greater <>().
Algorithm
Begin Declare v of vector type. Initialize some values into v in array pattern. Print “Elements before sorting”. for (const auto &i: v) print all the values of variable i. Print “Elements after sorting”. Call sort(v.begin(), v.end(), greater <>()) function to sort all the elements in descending order of v vector. for (const auto &i: v) print all the values of variable i. End.
This is a simple example of sorting a vector in C++:
Example
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> v = { 10, 9, 8, 6, 7, 2, 5, 1 }; cout<<"Elements before sorting"<<endl; for (const auto &i: v) cout << i << ' '<<endl; cout<<"Elements after sorting"<<endl; sort(v.begin(), v.end(), greater <>()); for (const auto &i: v) cout << i << ' '<<endl; return 0; }
Output
Elements before sorting 10 9 8 6 7 2 5 1 Elements after sorting 10 9 8 7 6 5 2 1
Advertisements