LearnFrenzy
Sign in Take a free test

Arrays and Vectors · Predict the Output · Question 14

Emptying a vector with pop_back in a loop Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 14 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<char> stack{'a', 'b', 'c', 'd'};
    while (!stack.empty()) {
        std::cout << stack.back();
        stack.pop_back();
    }
    std::cout << ' ' << stack.size() << '\n';
    return 0;
}
  • A dcba 0 Correct
  • B abcd 0
  • C dcba 4
  • D d 3
Correct Answer: Option A

back() and pop_back() use the vector as a stack: last in, first out.

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