Open In App

How to Clear All Elements from a List in C++?

Last Updated : 18 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, std::list is a container provided by the Standard Template Library (STL) that represents a doubly linked list and stores elements in non-contiguous memory locations. In this article, we will learn how to clear all elements from a list in C++.

Example:

Input: 
myList = {10, 20, 60, 80, 90};

Output: 
//After clearing, the list is empty
myList = {};

Remove All Elements from a List in C++

To clear all elements from a std::list in C++, we can use the std::list::clear() function. This function removes all the elements from the list container, thus making the list empty and reducing its size to 0.

Syntax to Clear All Element From a List in C++

list_Name.clear();

C++ Program to Clear All Elements from a List 

The below example demonstrates the use of the std::list::clear() function to clear all elements from a std::list in C++ STL.

C++
// C++ program to demonstrate the use of the
// std::list::clear() function to clear all elements from a
// std::list

#include <iostream>
#include <list>
using namespace std;

int main()
{
    // Creating a list
    list<int> myList = { 10, 20, 60, 80, 90 };

    // Printing the elements of the list
    cout << "List Elements: ";
    for (int ele : myList) {
        cout << ele << " ";
    }
    cout << endl;
    // Printing the size of the list before clearing it
    cout << "Before clearing, the list has "
         << myList.size() << " elements" << endl;

    // Clearing the list
    myList.clear();

    // Printing the size of the list after  clearing it
    cout << "After clearing, the list has " << myList.size()
         << " elements" << endl;

    return 0;
}

Output
List Elements: 10 20 60 80 90 
Before clearing, the list has 5 elements
After clearing, the list has 0 elements

Time Complexity: O(N), where N is the number of elements in the list.
Auxiliary Space: O(1)




Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads