【C++】清空一個C++棧的快速方法

來源: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.html

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

或者:post

2.spa

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

轉載於:https://www.cnblogs.com/nibolyoung/p/11005194.htmlcode