Skip to content
Exercise · Classes and OOP · lesson 13 of 13

Exercise: IntStack class

Write the class IntStack, a stack of integers: the number added last is removed first. Keep the numbers in a std::vector<int>; add the fields yourself. void push(int value) puts a number on top, void pop() removes the top number, and int top() const returns it. bool empty() const tells whether the stack is empty, and int size() const tells how many numbers it holds.

  • for a new stack, empty() → true, size() → 0
  • after push(1) and push(2): top() → 2, size() → 2
  • after one more pop(): top() → 1

Constraints: pop() and top() are called only on a non-empty stack.

int_stack.cpp — cpp
cpp · 23 lines
Ctrl+Enter run · Esc leave editor