stack

Overview

estd::stack provides the functionality of a stack, specifically a LIFO (last-in, first-out) data structure.

The class template acts as a wrapper to the underlying container. Only stack specific functions (push and pop) are provided. stack appends and removes the elements to/from the back of the underlying container. The back of the underlaying container can be considered as the top of the stack.

The stack uses an encapsulated object of vector (by default) as its underlying container.

The ‘declare’ pattern in estd::declare::stack is to declare a statically-sized stack object of size N which stores maximum size of stack at runtime, increasing RAM usage.

Usage

The usage constraints and guidelines apply for stack.

Constraints

stack has a fixed max_size which is given at the time of declaration.

Expanding further than the max_size is not possible results in a runtime error.

Usage guidance

estd::declare::stack must be used to create a stack, estd::stack can only refer to an existing stack objects.

The size should be checked before push or pop operations to avoid runtime error.

Example

The following example shows various ways to construct a stack.

// Construction of a default estd::declare::stack that stores up to 10 elements
::estd::declare::stack<int32_t, 10> a;
// Construction of a stack from another stack
::estd::declare::stack<int32_t, 10> b(a);

The next piece of code shows an example of accessing elements from a stack.

// Declare an empty stack
::estd::declare::stack<int32_t, 5> s;
::estd::stack<int32_t>& cs = s;
s.push(1);
ASSERT_EQ(1, s.top());
ASSERT_EQ(1, cs.top());
s.push() = 2;
ASSERT_EQ(2, s.top());

The next example shows various capacity operations performed on a stack.

// Declare an empty stack
::estd::declare::stack<int32_t, 10> s;
s.push(1);
ASSERT_EQ(1U, s.size());
s.push() = 2;
ASSERT_EQ(2U, s.size());
s.pop();
ASSERT_EQ(1U, s.size());
s.pop();
ASSERT_EQ(0U, s.size());
ASSERT_EQ(10U, s.max_size());
ASSERT_TRUE(s.empty());
for (estd::stack<int32_t>::size_type i = 0; i < s.max_size(); ++i)
{
    s.push(0);
}
ASSERT_TRUE(s.full());

The example shows various modifying operations performed on a stack.

    // Declare an empty stack
    ::estd::declare::stack<int32_t, 10> s;
    int32_t i = 1;
    while (!s.full())
    {
        s.emplace().construct(i);
        ASSERT_EQ((size_t)i, s.size());
        ASSERT_EQ(i, s.top());
        ++i;
    }
    ASSERT_EQ(s.max_size(), s.size());
    ASSERT_TRUE(s.full());