list::clear() in C++ STL
Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists.
clear() function is used to remove all the elements of the list container, thus making it size 0.
Syntax :
listname.clear() Parameters : No parameters are passed. Result : All the elements of the list are removed ( or destroyed )
Examples:
Input : list{1, 2, 3, 4, 5};
list.clear();
Output : list{}
Input : list{};
list.clear();
Output : list{}
Errors and Exceptions
1. It has a no exception throw guarantee.
2. Shows error when a parameter is passed.
// CPP program to illustrate // Implementation of clear() function #include <iostream> #include <list> using namespace std; int main() { list<int> mylist{ 1, 2, 3, 4, 5 }; mylist.clear(); // List becomes empty // Printing the list for (auto it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it; return 0; } |
Output:
No Output
Related Article : Delete elements in C++ STL List
Recommended Posts:
- Find the Deepest Node in a Binary Tree Using Queue STL - SET 2
- C++ program to compare two Strings using Operator Overloading
- not1 and not2 function templates in C++ STL with Examples
- Go vs C++
- Trie Data Structure using smart pointer and OOP in C++
- Modular Exponentiation of Complex Numbers
- std::hash class in C++ STL
- History of C++
- What are Forward declarations in C++
- __builtin_inf() functions of GCC compiler
- Structures in C++
- Variables in C++
- Implementing Forward Iterator in BST
- Count substrings that contain all vowels | SET 2
- Machine Learning in C++
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



