int arr[5]; int top = -1; // Direct array use arr[++top] = 10; arr[++top] = 20; arr[++top] = 30; std::cout << arr[top] << std::endl; --top; std::cout << arr[top] << std::endl; // Using stack abstraction std::stack<int> s; s.push(10); s.push(20); s.push(30); std::cout << s.top() << std::endl; s.pop(); std::cout << s.top() << std::endl;
The direct array manipulation uses an integer 'top' to track the last element index. Incrementing top before assignment adds elements. Printing arr[top] shows the last pushed value. Decrementing top simulates pop. The stack abstraction uses push and pop methods with top() to access the last element. Both print the same sequence: 30 then 20.
Stack abstraction provides methods like push, pop, and top that internally manage the size and prevent invalid access. Direct array use requires manual tracking of indices and risks out-of-bounds errors.
int arr[3]; int top = -1; arr[++top] = 5; arr[++top] = 10; arr[++top] = 15; arr[++top] = 20; // Problematic line std::cout << arr[top] << std::endl;
The array size is 3, so valid indices are 0,1,2. The code increments top to 3 and tries to assign arr[3] = 20, which is out of bounds and causes a runtime error.
#include <iostream> #include <stack> int main() { int arr[4]; int top = -1; std::stack<int> s; arr[++top] = 1; arr[++top] = 2; s.push(3); s.push(4); std::cout << arr[top] << std::endl; std::cout << s.top() << std::endl; --top; s.pop(); std::cout << arr[top] << std::endl; std::cout << s.top() << std::endl; return 0; }
Initially, arr has 1 and 2 at indices 0 and 1, top=1. Stack has 3 and 4 pushed, top is 4. Printing arr[top] prints 2, stack top prints 4. After decrementing top and popping stack, arr[top] is 1, stack top is 3.
Stack abstraction encapsulates the implementation details. If the internal data structure changes, code using the stack does not need modification, improving maintainability.
