











List in STL C++
About List in STL :
List in STL is defined as the container used to store elements in the contiguous manner and allow insertion and deletion at any position.


Syntax of List :
list< data_type> list_name;
In STL, List store the elements on a contiguous memory, but vector stores on a non-contiguous memory. List is a contiguous container, whereas vector is a non-contiguous container. As it takes a long time to move all the elements, insertion and deletion in the midst of the vector are quite expensive. This issue is solved by linklist, which is implemented using a list container. The list offers an effective method for insertion and deletion operations and facilitates bidirectional communication. List traversal is longer because elements are read sequentially, whereas a vector allows for random access.
Functions in List :
Function | Working |
---|---|
push_back() | insert an element to the back end of the list. |
push_front() | insert an element to the front end of the list. |
size() | give the number of elements present in the list. |
empty() | tells whether thelist is empty or not. |
pop_front() | remove the element from front of the list. |
Example of List in STL :
#include <iostream> #includ<bits/stdc++.h> using namespace std; int main() { list< int>lt = {2,5,4,6,7,8}; cout<<"The elements in the list :"; for(auto it : lt){ cout<< it<<" "; } return 0; }
Output :
The elements in the list :2 5 4 6 7 8
In the above program, we take the list lt with elements 2, 5 , 4, 6, 7 ,8 and print them on the screen.
Example of List in STL:
#include<iostream> #include<bits/stdc++.h> using namespace std; int main() { list< int>lt = {2,5,4,6,7,8}; lt.push_back(9); lt.push_front(12); cout<<"The elements in the list :"; for(auto it : lt){ cout<< it<<" "; } cout<< endl; lt.pop_back(); lt.pop_back(); cout<<"The elements in the list after applying pop function : "; for(auto it : lt){ cout<< it<<" "; } cout<< endl; cout<<"The size of list : "<< lt.size(); return 0; }
Output :
The elements in the list :12 2 5 4 6 7 8 9 The elements in the list after applying pop function : 12 2 5 4 6 7 The size of list : 6
In the above program, we take the list lt , applying different functs push_back, pop_back, push_front and see the result on the list.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment