[英]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
我想知道為什么這段代碼不起作用,我想以與 java 中相同的方式在方括號內打印我的堆棧,即[ 1 2 3 4 5 ]
。 請幫助我確定我做錯了什么。
問題(錯誤)是printHelper
需要兩個參數,但您僅在編寫時傳遞:
//----------v--->you've passed only 1
printHelper(s);
要解決這個問題(錯誤),只需傳遞兩個參數,如下所示:
//----------vv--v---------->pass 2 arguments as expected by printHelper
printHelper(os, s);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.