c++ - 如何获得 'stack based' std::stack? (固定最大尺寸)

标签 c++ stack c++17

根据std::stack引用:

The type of the underlying container to use to store the elements. The container must satisfy the requirements of SequenceContainer. Additionally, it must provide the following functions with the usual semantics:

back()
push_back()
pop_back() 

The standard containers std::vector, std::deque and std::list satisfy these requirements. By default, if no container class is specified for a particular stack class instantiation, the standard container std::deque is used.

所有这些都是基于堆的容器。

以下实际编译():

std::stack<int, std::array<int, 12> > stack_of_months;

直到 push 被调用。

是否有一些技巧可以轻松包装 std::array 以支持这些方法,以便它可以在堆栈中使用?

最佳答案

您应该能够使用 Boost 的 static_vector :

static_vector is a sequence container like with contiguous storage that can change in size, along with the static allocation, low overhead, and fixed capacity.

一个工作示例:

std::stack<int, boost::container::static_vector<int, 4>> s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
// s.push(5); // would throw

@PaulMcKenzie 是的,它使用堆栈作为存储(当然,如果对象本身存储在堆栈中):

The number of elements in a static_vector may vary dynamically up to a fixed capacity because elements are stored within the object itself similarly to an array.

现场演示:https://wandbox.org/permlink/Gi40FrB0yX8dIwfA .

关于c++ - 如何获得 'stack based' std::stack? (固定最大尺寸),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58288035/

相关文章:

创建指向内存地址的符号链接(symbolic link)。 (剧透 : Stripe CTF contest)

c++ - Box2D:让 body 随机下降

memory - Linux size命令,为什么bss和data部分不为零?

c++ - 如何更新指针集 C++?

python - 使用两个堆栈 Python 实现一个队列

C++堆栈实现,不在函数中保留内存

c++ - 为什么这个初始化列表不能匹配模板参数?

c++ - 当将新对象分配给其地址时,是否必须销毁该对象?

c++ - 使用 share_from_this 而不是 this 指针

c++ - 没有这样的文件(头文件)错误