Skip to main content

std::stack empty() method

// Const version only
[[nodiscard]] bool empty() const;

Checks if the container has no elements, i.e. whether c.empty().

Parameters

(none)

Return value

true if the container is empty, false otherwise.

Complexity

Constant - O(1).

Exceptions

(none)

Why [[nodiscard]]?

The [[nodiscard]] attribute is an attribute that invokes compiler warnings whenever a function has been called and it's result has been discarded.

The reason behind the nodiscard being applied only to the empty method is that it's likely that the programmer might confuse the adjective empty ( which would mean - is this container empty?) for the verb empty (which would mean - please empty this container for me.).

Example

Main.cpp
#include <algorithm>
#include <iostream>
#include <stack>

int main()
{
std::cout << std::boolalpha;

std::stack<int> container;

std::cout << "Initially, container.empty(): " << container.empty() << '\n';

container.push(42);
std::cout << "After adding elements, container.empty(): " << container.empty() << '\n';
}
Output
Initially, container.empty(): true
After adding elements, container.empty(): false

std::stack empty() method

// Const version only
[[nodiscard]] bool empty() const;

Checks if the container has no elements, i.e. whether c.empty().

Parameters

(none)

Return value

true if the container is empty, false otherwise.

Complexity

Constant - O(1).

Exceptions

(none)

Why [[nodiscard]]?

The [[nodiscard]] attribute is an attribute that invokes compiler warnings whenever a function has been called and it's result has been discarded.

The reason behind the nodiscard being applied only to the empty method is that it's likely that the programmer might confuse the adjective empty ( which would mean - is this container empty?) for the verb empty (which would mean - please empty this container for me.).

Example

Main.cpp
#include <algorithm>
#include <iostream>
#include <stack>

int main()
{
std::cout << std::boolalpha;

std::stack<int> container;

std::cout << "Initially, container.empty(): " << container.empty() << '\n';

container.push(42);
std::cout << "After adding elements, container.empty(): " << container.empty() << '\n';
}
Output
Initially, container.empty(): true
After adding elements, container.empty(): false