简体   繁体   English

重载 << 运算符以在 C++ 中打印堆栈

[英]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 ] .我想知道为什么这段代码不起作用,我想以与 java 中相同的方式在方括号内打印我的堆栈,即[ 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:问题(错误)是printHelper需要两个参数,但您仅在编写时传递:

//----------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工作演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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