Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Overloading << operator for printing stack in c++

#include <iostream>
#include <ostream>
#include <bits/stdc++.h>
using namespace std;
void printHelper(ostream& os,stack<int>& s){
    if(s.empty())
        return ;
    int val = s.top();
    s.pop();
    printHelper(s);

    os << val << " ";
    s.push(val);
}

ostream& operator<<(ostream& os,stack<int>& s){
    os << "[ ";
    printHelper(os,s);
    os << "]\n";
    return os;
}

int main(){
    #ifndef ONLINE_JUDGE
        freopen("input.txt","r",stdin);
        freopen("output.txt","w",stdout);
    #endif
    stack<int> s;
    for(int i = 0;i<5;i++){
        s.push(i+1);
    }
    cout << s;
    return 0;
}

// c++ stack -- push pop top size empty

I want to know as to why this code is not working, I want to print my stack in the same fashion as in java within square brackets i.e [ 1 2 3 4 5 ]. Please help me identify what have i done wrong.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The problem(error) is that printHelper expects two arguments but you’re passing only when when writing:

//----------v--->you've passed only 1
printHelper(s);

To solve this(the error) just pass the two arguments as shown below:

//----------vv--v---------->pass 2 arguments as expected by printHelper
printHelper(os, s);

Working demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading