C++ std::list::empty

The std::list::empty function checks whether the list container is empty. It returns true if the list has no elements, and false otherwise. This function is a convenient way to test for an empty container without comparing its size to zero.


Syntax of std::list::empty

</>
Copy
bool empty() const noexcept;

Parameters

The std::list::empty function does not take any parameters.

Return Value

Returns a bool value:

  • true: The list is empty.
  • false: The list contains at least one element.

Exceptions

The std::list::empty function does not throw exceptions as it is marked noexcept. It is a safe operation that simply checks whether the list container has any elements.


Examples for std::list::empty

Example 1: Checking If a List Is Empty

This example demonstrates how to use empty() to check whether a list contains elements:

</>
Copy
#include <iostream>
#include <list>

int main() {
    std::list<int> myList;

    if (myList.empty()) {
        std::cout << "The list is empty." << std::endl;
    } else {
        std::cout << "The list is not empty." << std::endl;
    }

    myList.push_back(10); // Add an element to the list

    if (myList.empty()) {
        std::cout << "The list is empty." << std::endl;
    } else {
        std::cout << "The list is not empty." << std::endl;
    }

    return 0;
}

Explanation:

  1. Define an empty list: A std::list named myList is initialized without elements.
  2. Check if the list is empty: The empty() function is called to check if the list is empty. Initially, it returns true.
  3. Add an element: The push_back() function adds an element to the list, making it non-empty.
  4. Check again: The empty() function is called again, and this time it returns false.

Output:

The list is empty.
The list is not empty.

Example 2: Avoiding Operations on an Empty List

This example demonstrates how to safely avoid operations on an empty list using empty():

</>
Copy
#include <iostream>
#include <list>

int main() {
    std::list<int> myList;

    if (!myList.empty()) {
        std::cout << "First element: " << myList.front() << std::endl;
    } else {
        std::cout << "Cannot access elements in an empty list." << std::endl;
    }

    return 0;
}

Explanation:

  1. Define an empty list: A std::list named myList is initialized without elements.
  2. Check before accessing: The empty() function is used to check whether the list is empty. Since it is empty, the program avoids accessing its elements and prints a message.

Output:

Cannot access elements in an empty list.