- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
forward_list::clear() and forward_list::erase_after() in C++ STL
In this article we will be discussing the working, syntax and examples of forward_list::clear() and forward_list::erase_after() functions in C++.
What is a Forward_list in STL?
Forward list are sequence containers that allow constant time insert and erase operations anywhere within the sequence. Forward lists are implemented as singly linked lists. The ordering is kept by the association to each element of a link to the next element in the sequence.
What is forward_list::clear()?
forward_list::clear() is an inbuilt function in C++ STL which is declared in <forward_list> header file. clear() is used when we have to remove all the elements of the forward list at once. This function destroys all the elements of the forward list and makes the size of forward list as zero.
Syntax
flist_container1.clear();
Parameters
This function accepts no parameters.
Return Value
This function returns nothing.
Example
Input: forward_list<int> forward = {1, 2, 3, 4}; forward.clear(); forward.size(); Output: 0
Example
#include <forward_list> #include <iostream> using namespace std; int main(){ forward_list<int> myList = { 10, 20, 30, 40 }; myList.clear(); for (auto i = myList.begin(); i!= myList.end(); ++i) cout << ' ' << *i; cout<<"List is cleared"; return 0; }
Output
If we run the above code it will generate the following output −
List is cleared
What is forward_list::erase_after()?
forward_list::erase_after() is an inbuilt function in C++ STL which is declared in <forward_list> header file. erase_after() is used when we want to remove elements in a forward list after a specific position. The size of the forward list is reduced by the number of elements removed.
Syntax
flist_container1.erase_after(unsigned int position);
Parameters
This function accepts one parameter which is the position from which we want to remove the elements
Return Value
This function returns nothing.
Example
Input: forward_list<int> forward = {1, 2, 3, 4}; forward.erased_after(2); Output: Forward list after erase_after() = 1 2 3
Example
#include <forward_list> #include <iostream> using namespace std; int main(){ forward_list<int> myList = { 10, 20, 30, 40, 50 }; forward_list<int>::iterator i; i = myList.begin(); myList.erase_after(i); cout<<"Elements are : "; for (auto i = myList.begin(); i!= myList.end(); ++i) cout << ' ' << *i; return 0; }
Output
If we run the above code it will generate the following output −
Elements are : 10 30 40 50