C++ bootcamp · Lab 38

Reverse a vector

easyVectors8 minLesson: Vectors

Read the question, write C++ on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

The first number is n, then n integers. Print them in reverse order, space-separated.

std::reverse edits the vector in place.

Input. n, then n integers.

Output. The values in reverse order, space-separated.

Constraints

  • 1 ≤ n ≤ 1000

Examples

Example 1
Input
5
1 2 3 4 5
Output
5 4 3 2 1
Hint
  1. std::reverse(v.begin(), v.end()); then print each value.
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
  int n;
  std::cin >> n;
  std::vector<int> v(n);
  for (int i = 0; i < n; i++) std::cin >> v[i];
  std::reverse(v.begin(), v.end());
  for (int x : v) std::cout << x << " ";
  std::cout << "\n";
  return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.