LearnFrenzy
Sign in Take a free test

Arrays and Vectors · Predict the Output · Question 16

Sorting a vector in descending order Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 16 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> v{40, 10, 30, 20, 50};
    std::sort(v.begin(), v.end(), std::greater<>());
    std::sort(v.begin() + 1, v.end() - 1);
    for (int x : v) std::cout << x << ' ';
    std::cout << '\n';
    return 0;
}
  • A 50 20 30 40 10 Correct
  • B 50 40 30 20 10
  • C 10 20 30 40 50
  • D 50 10 20 30 40
Correct Answer: Option A

The first sort gives 50 40 30 20 10. The second sorts only the middle three (40 30 20) ascending, leaving 50 and 10 in place.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links