简体   繁体   中英

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 ie [ 1 2 3 4 5 ] . Please help me identify what have i done wrong.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM