来源:https://stackoverflow.com/questions/40201711/how-can-i-clear-a-stack-in-c-efficiently/40201744

传统方法,使用循环:

#define elemType int 
void clearStack(stack<elemType> &s){
    while (!s.empty()){
        s.pop();
    }
}

不使用循环的方法:

1.

void clearStack(stack<elemType> &s){
    s = stack<elemType>();
}

或者:

2.

void clearStack(stack<elemType> &s){
    stack<elemType>().swap(s);
}
posted on 2019-06-11 18:08  nibolyoung  阅读(4831)  评论(0编辑  收藏  举报