Search code examples
c++stackstdvector

How can I print out the elements of my Stack class in C++ using std::vector and std::cout?


I need to print out elements of my Stack class, but I have no idea how to do so.

I'm currently working on the Tower of Hanoi problem, and to do so I have created a Stack class, which is basically a vector of cubes (created also the Cube class, which is inheriting a Shape class):

Stack.h

#pragma once
#include <vector>
#include "Cube.h"
#include <ostream>

namespace uiuc{
    class Stack{
        private:
            std::vector<Cube> stackOfCubes;
            int size_;
        public:
            Cube& pop();//gets the last cube of the stack and removes it
            void push(Cube cube);//pushes a cube into the stack 
            void peek();//prints out ALL the stack
            int size();
        friend std::ostream& operator<<(std::ostream& os, const Stack& stack){
            return stack.stackOfCubes;
        };
    };
}

I want to work on the peek() method, which prints out ALL the stack of cubes, but nonetheless I have no idea how to do so since std::cout doesn't know how to print out class objects.

I have found on other questions that I should overload operator<<, but it says the following error when I try to return the stackOfCubes:

a reference of type "std::ostream &" (not const-qualified) cannot be initialized with a value of type "const std::vector<uiuc::Cube, std::allocator<uiuc::Cube>>


Solution

  • The error message is telling you that you can't initialize a std::ostream& reference with a const std::vector<Cube> object, which is what your return stack.stackOfCubes; statement is trying to do.

    Your operator<< should not return the stack at all, it needs to return the provided ostream instead. Your operator<< should write the contents of the stack to that stream, eg:

    friend std::ostream& operator<<(std::ostream& os, const Stack& stack){
        // iterate stack.stackOfCubes, writing each Cube to os as needed...
        return os;
    };
    

    For example:

    class Cube : public Shape {
        ...
        friend std::ostream& operator<<(std::ostream& os, const Cube& cube){
            // write cube members to os as needed...
            return os;
        }
    };
    
    class Stack {
        ...
        friend std::ostream& operator<<(std::ostream& os, const Stack& stack){
            for(const Cube &cube : stack.stackOfCubes) {
                os << cube;
            }
            return os;
        }
    };