Skip to content
Exercise · Classes and OOP · lesson 8 of 15

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.

Do not add extra #include lines unless the task says so explicitly.

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

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way