C++中关于堆栈操作的问题

这是我在做将堆栈升序排序的时候遇到的问题,请教一下为什么第二个Print()函数不输出结果。

#include <iostream>
#include <stack>
using namespace std;
void StackSort(stack<int>& s){
    if(s.empty()||s.size()==1)
        return;
    stack<int> tmpStack;
    int first=s.top();
    tmpStack.push(first);
    s.pop();
    while(!s.empty()){
        int top=s.top();
        s.pop();

        while(!tmpStack.empty()&&top>tmpStack.top()){
            int tmp=tmpStack.top();
            tmpStack.pop();
            s.push(tmp);
        }
        tmpStack.push(top);
    }
    while(!tmpStack.empty()){
        int tmpFirst=tmpStack.top();
        tmpStack.pop();
        s.push(tmpFirst);
    }
}
void Print(stack<int>& s){
    while(!s.empty()){
        cout<<s.top();
        s.pop();
    }
}
int main(int argc, char** argv) {
    stack<int> s;
    s.push(5);
    s.push(8);
    s.push(6);
    s.push(2);
    s.push(3);
    Print(s);
    StackSort(s);
    Print(s);
    return 0;
}

打印时候不应该用引用,而且建议结尾加个换行,这样更好看一些:

#include <iostream>
#include <stack>
using namespace std;
void StackSort(stack<int>& s){
    if (s.empty() || s.size() == 1)
        return;
    stack<int> tmpStack;
    int first = s.top();
    tmpStack.push(first);
    s.pop();
    while (!s.empty()){
        int top = s.top();
        s.pop();

        while (!tmpStack.empty() && top > tmpStack.top()){
            int tmp = tmpStack.top();
            tmpStack.pop();
            s.push(tmp);
        }
        tmpStack.push(top);
    }
    while (!tmpStack.empty()){
        int tmpFirst = tmpStack.top();
        tmpStack.pop();
        s.push(tmpFirst);
    }
}
void Print(stack<int> s){
    while (!s.empty()){
        cout << s.top();
        s.pop();
    }
    cout << endl;
}
int main(int argc, char** argv) {
    stack<int> s;
    s.push(5);
    s.push(8);
    s.push(6);
    s.push(2);
    s.push(3);
    Print(s);
    StackSort(s);
    Print(s);
    return 0;
}

额,你注意看你的

void Print(stack<int>& s){
    while(!s.empty()){
        cout<<s.top();
        s.pop();
    }
}

将s所有item都pop出来了,并且你函数参数还是传引用,所以直接改变了s的内容,你去除&就行了

void Print(stack<int> s){
    while(!s.empty()){
        cout<<s.top();
        s.pop();
    }
}