Read the question, write C++ on the right, then Run or Check.
QuestionHint and solution stay closed until you open them
Read a line of integers and print them sorted descending, space-separated.
std::sort with std::greater<int>{} (or a lambda) reverses the usual ascending order.
Input. Integers separated by spaces.
Output. The same values, descending, space-separated.
Examples
Input
5 3 1 4 2
Output
5 4 3 2 1
Input
3 3 1
Output
3 3 1
Hint
- std::sort(v.begin(), v.end(), std::greater<int>{});
- Or sort ascending and print from the back.
Show correct code
Peek only after you have tried. You can still Check your own version.
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
int main() {
std::vector<int> v;
int x;
while (std::cin >> x) v.push_back(x);
std::sort(v.begin(), v.end(), std::greater<int>{});
for (int n : v) std::cout << n << " ";
std::cout << "\n";
return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.