[英]Is std::stack contiguous?
I wanted to find the maximum element in a stack, and thought of using std::max_element
.我想找到堆栈中的最大元素,并考虑使用
std::max_element
。
Then I came to know that std::stack
does not have begin()
and end()
functions.然后我才知道
std::stack
没有begin()
和end()
函数。 After surfing the net, I saw a hack:在网上冲浪后,我看到了一个 hack:
stack<int> s({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
auto end = &s.top() + 1; // instead of std::end
auto begin = end - s.size(); // instead of std::begin
cout << "Max = " << *max_element(begin, end);
It does seem to work, you can see it online .好像还可以,网上可以看。
But when I submitted my code, it failed some of the test cases.但是当我提交我的代码时,它失败了一些测试用例。 Is
std::stack
really contiguous? std::stack
真的是连续的吗?
It depends on the underlying container of the std::stack
:它取决于
std::stack
的底层容器:
template <class T, class Container = deque<T>> class stack;
The class template acts as a wrapper to the underlying container
class 模板充当底层容器的包装器
By default, Container = deque<T>
.默认情况下,
Container = deque<T>
。 And std::deque
is not contiguous:并且
std::deque
不连续:
the elements of a deque are not stored contiguously
双端队列的元素不是连续存储的
Therefore,所以,
stack<int> s;
is not contiguous because std::deque
is not contiguous.不连续,因为
std::deque
不连续。
However,然而,
typical implementations (of
std::deque
) use a sequence of individually allocated fixed-size arrays(
std::deque
的典型实现)使用一系列单独分配的固定大小 arrays
That is why some of the test cases failed;这就是一些测试用例失败的原因; the contiguity broke when the stack grew more than the size of one of the underlying fixed-size arrays.
当堆栈增长到超过底层固定大小 arrays 之一的大小时,连续性就会中断。
If the underlying container is specified explicitly (the standard containers std::vector
and std::list
satisfy the requirements apart from std::deque
) and if that container is contiguous, then that stack is also contiguous.如果显式指定了底层容器(标准容器
std::vector
和std::list
满足除std::deque
之外的要求)并且如果该容器是连续的,则该堆栈也是连续的。
For example,例如,
stack<int, vector<int>> s;
is contiguous because std::vector
is contiguous.是连续的,因为
std::vector
是连续的。
The contiguity of std::stack
is determined by the contiguity of its underlying container. std::stack
的连续性由其底层容器的连续性决定。
Is std::stack
contiguous? std::stack
是连续的吗? I would say, it doesn't matter.我会说,没关系。
std::stack
is not a container, but an adapter, and its idea is the stack abstraction and a deliberate restriction of interfaces. std::stack
不是容器,而是适配器,其思想是堆栈抽象和对接口的刻意限制。
Even if it were contiguous, accessing elements of std::stack
by any means but .top()
would be a violation of its semantics.即使它是连续的,以任何方式访问
std::stack
的元素,但.top()
将违反其语义。 If you need such an access, you should not use std::stack
in the first place.如果你需要这样的访问,你首先不应该使用
std::stack
。 Don't confuse the reader of your code.不要混淆您的代码的读者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.