C++ <list> empty Function

C++ container class <list>


emptyis used in list forcheck whether the linked list is emptyof the function.

emptyIt is a member function of the container class, returning whether the linked list is empty.

This is the most commonly used function to check the state of a linked list, compared tosize() == 0More efficient.

Word Definitions: emptyIt means "empty", i.e., checks whether the linked list is empty.


Basic syntax and parameters

Syntax format

bool empty() const;

Function description

  • Return Value: If the linked list is empty, returntrue, otherwise returnfalse。

Example

Example 1: Check whether the linked list is empty

Example

#include <iostream>
#include <list>

void processList(const std::list<int>& lst) {
    if(lst.empty()) {
        std::cout << The list is empty << std::endl;
    } else {
        std::cout << The list has << lst.size() << " elements" << std::endl;
    }
}

int main() {
    std::list<int> emptyList;
    processList(emptyList);

    std::list<int> numbers = {1, 2, 3};
    processList(numbers);

    return 0;
}

Expected running result:

链表为空
链表有 3 个元素

C++ container class <list>

other extensions