2 minute read

Introduction

The std::stack function is a highly useful function that allows us to create and manipulate last-in-first-out (LIFO) stacks in the C++ programming language. However, we can often get errors from the compiler such as:

error: ‘stack’ is not a member of ‘std’

This error is pretty straight-forward to fix as we will see below.

Potential causes

The stack is not a member of std error could be caused by multiple reasons.

Fix #1: Add stack to your dependencies

Essentially, the std::stack function needs to have access to the stack module in order to be executed by the compiler.

Therefore, you must add the following #include header to the top of your code (in the include(s) part) such as:

#include <stack> //Add this

int main() {
    std::stack<int> myStack;
    myStack.push(1);
    return 0;
}

The compiler should now recognize the std::stack function, thus fixing the stack is not a member of std error.

Fix #2: Using namespace std

Note that we have previously typed: std::stack instead of stack. We can type “stack” only if we are declaring that we are using its namespace.

In other words, we would need to type “using namespace std” in the header if we only want to type stack (which is obviously shorter) instead of std::stack. For instance, we can have something like:

#include <stack>
using namespace std; //Add this

int main() {
    stack<int> myStack;
    myStack.push(1);
    return 0;
}

It is okay to type std::stack without typing “using namespace std”. In fact, it is generally recommended to type the full std::stack function name (and therefore avoiding using namespace std) when working with multiple libraries because it can reduce future confusion.

However, if you still want to type “stack” instead of “std::stack”, then you need to add “using namespace std” to the header

References

Read more about the std::stack function here: https://en.cppreference.com/w/cpp/container/stack