how to print out all elements in a std::stack or std::queue conveniently

后端 未结 8 1735
忘掉有多难
忘掉有多难 2020-12-14 20:46

If I do not to want to create a new container in order to do so?

8条回答
  •  清歌不尽
    2020-12-14 21:31

    Posting b/c I found this useful for debugging. Pop from original into a temp and then pop from temp back into original:

    template 
    void dump_stack(std::stack& stack) {
      std::stack temp;
      while (!stack.empty()) {
        T top = stack.top(); stack.pop();
        std::cout << top << " ";
        temp.push(top);
      }
      while (!temp.empty()) {
        T top = temp.top(); temp.pop();
        stack.push(top);
      }
    }
    

提交回复
热议问题