如何遍历一个 std::stack(详细揭秘)
首先我们可以快速明确一点,stack 本身只是一个适配器,不负责干活,只是给你用别的数据结构维护数据然后提供一个栈的封装。默认用的是 deque(所以空间大的万恶之源也是底层的双端队列而不是栈结构本身)。举个例子,不想被卡空间的话,stack<int,list<int>> 就是一个还可以的选择。
但是众所周知 stack 有一个很难受的问题,那就是没法遍历。如果要获得 stack 里的所有元素,必须一个个 pop 出来然后 push 回去,巨大阴间,不如手写。于是这一天,又一次被恶心到的 ut 翻了翻 stack 的源代码。
protected:
// See queue::c for notes on this name.
_Sequence c;
已经可以猜到这个 c 就是我们要的底层容器了,不过我们依然可以去 queue 那边逛逛。
protected:
/* Maintainers wondering why this isn't uglified as per style
* guidelines should note that this name is specified in the standard,
* C++98 [23.2.3.1].
* (Why? Presumably for the same reason that it's protected instead
* of private: to allow derivation. But none of the other
* containers allow for derivation. Odd.)
*/
/// @c c is the underlying container.
_Sequence c;
这确实印证了我们的猜想,但问题是它是被保护的,换句话说我们必须得开个类继承这个 stack 才能遍历,那为什么不手写???
这里我们有一种很简单的方法(专在 OI 之类的场合),注意到 #include 的本质是把别的文件的内容复制过来,比如一个 #include<stack> 就是把那个库的内容复制了过来。既然是直接复制,在前面放点东西当然是没问题的。
于是我们
#define protected public
#include <bits/stdc++.h>
现在就可以访问这个 c 了。
ut 第一次试这个东西的题代码无关内容比较多,挂个核心放过来吧。
stack<pair<int, int>> stk;
for (ranges::sort(qry); auto [l, r] : qry) {
while (!stk.empty() && stk.top().second >= r) stk.pop();
if (stk.empty() || stk.top().first < l) stk.emplace(l, r);
}
for (auto [l, r] : stk.c) es[r].push_back(l);
无视无关部分,我们成功地遍历到了这个底层的 deque,也就确实遍历到了这个栈。
进一步地,栈本身不维护任何东西,一切数据都是靠的这个底层容器。换句话说,我们实际上也可以如法炮制修改栈中元素等,或者最次就是 stk.c.clear() 爽完就跑。queue 可以用完全一样的方法处理。
以上。
鉴于评论有提再说几句
- 为啥不手写?
总有时候想偷个懒吧,比如我(
空间也是一个值得考量的点,而且可以推广到 queue(
- define 逆天思路
以前看到过一个 bitset 有人建议 #define private public 的,如法炮制了一下(
没有任何价值且令人不适的评论会被控。