C++ <list> clear Function

C++ container class <list>


clearis used for in listClear all elementsThe function is the simplest and most efficient way to clear a container.

clearIt is a member function of the container class, used to delete all elements in the linked list, making the list empty.

After calling, the linked list'ssize()will become 0.

Word Definitions: clearIt means "clear," i.e., delete all elements.


Basic syntax and parameters

clearIt is a member function of the container class, and calling it requires no parameters.

Syntax format

void clear();

Function description

  • Return Value: void(no return value).
  • Effect: Delete all elements in the linked list,size()becomes 0.

Example

Example 1: Clear the linked list

Example

#include <iostream>
#include <list>

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

    std::cout << "Before clearing - size: " << numbers.size() << std::endl;

    numbers.clear();

    std::cout << "After clearing - size: " << numbers.size() << std::endl;

    return 0;
}

Expected output:

清空前 - size: 5
清空后 - size: 0

Example 2: Reuse after clearing

Example

#include <iostream>
#include <list>

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

    data.push_back(1);
    data.push_back(2);
    std::cout << "After the first addition: " << data.size() << std::endl;

    data.clear();

    data.push_back(10);
    data.push_back(20);
    data.push_back(30);
    std::cout << "After clearing and re-adding: ";
    for(int n : data) std::cout << n << " ";
    std::cout << std::endl;

    return 0;
}

Expected output:

第一次添加后: 2
清空后重新添加: 10 20 30

C++ container class <list>

other extensions