LearnFrenzy
Sign in Take a free test

Arrays and Vectors · Predict the Output · Question 15

Iterating a vector backwards with rbegin Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 15 Back to Exercise

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

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

int main() {
    std::vector<int> v{1, 2, 3, 4, 5};
    for (auto it = v.rbegin(); it != v.rend(); ++it)
        if ((it - v.rbegin()) % 2 == 0) std::cout << *it << ' ';
    std::cout << '|' << *(v.end() - 2) << '\n';
    return 0;
}
  • A 5 3 1 |4 Correct
  • B 1 3 5 |4
  • C 5 4 3 2 1 |4
  • D 5 3 1 |5
Correct Answer: Option A

Reverse iterators start at the last element; printing every second one visits 5, 3, 1. (Jumping with it += 2 would step past rend(), which is undefined behaviour.) end() is one past the last element, so end() − 2 is the 4.

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