Consider a stack where you push 10, then 20, then 30. You then peek the top element without popping it. What is the output?
std::stack<int> s; s.push(10); s.push(20); s.push(30); int topElement = s.top(); std::cout << topElement << std::endl;
Remember, the top element is the last one pushed onto the stack.
The last element pushed is 30, so peeking the top returns 30 without removing it.
Given an empty stack, what will happen if you call the top() method?
std::stack<int> s; int topElement = s.top(); std::cout << topElement << std::endl;
Think about what happens if you try to access an element that does not exist.
Calling top() on an empty stack leads to undefined behavior or runtime error because there is no element to return.
What is wrong with this code snippet that tries to peek the top element?
std::stack<int> s; s.push(5); int topElement = s.pop(); std::cout << topElement << std::endl;
Check the return type of pop() in the stack API.
The pop() method does not return the top element; it only removes it. Assigning its result to a variable causes a compile error.
Given the following operations on a stack, what is printed?
std::stack<int> s; s.push(1); s.push(2); s.push(3); std::cout << s.top() << std::endl; s.pop(); std::cout << s.top() << std::endl;
Remember that pop() removes the top element, so the next top() shows the new top.
First top is 3, after popping 3, the new top is 2.
Choose the correct statement about the top() operation on a stack.
Think about what happens if you call top() on an empty stack in C++ STL.
In C++ STL, top() returns the top element without removing it but calling it on an empty stack causes undefined behavior (no exception is thrown).
