List push_back() function in C++ STL

C++Server Side ProgrammingProgramming

In this article we will be discussing the working, syntax and examples of list:: push_back() function in C++.

What is a List in STL

List is a data structure that allows constant time insertion and deletion anywhere in sequence. Lists are implemented as doubly linked lists. Lists allow non-contiguous memory allocation. List perform better insertion extraction and moving of element in any position in container than array, vector and deque. In List the direct access to the element is slow and list is similar to forward_list, but forward list objects are single linked lists and they can only be iterated forwards.

What is list::push_back()

list::push_back() is an inbuilt function in C++ STL which is declared in header file. push_back() is used to push/insert the element at the end of the list container. push_back also increases the size of the container by 1.

Syntax

list_name. push_back (int ele);

This function accept one parameter only, i.e. the element we want to push/insert at the back/last of the list_name container.

Return value

This function returns nothing. It will only insert the element in the list container.

Example

 Live Demo

#include<bits/stdc++.h>
using namespace std;
int main(){
   //create a list
   list<int> myList;
   //Displaying the initial size of a list
   cout<<"size of the list: "<<myList.size()<< endl;
   //inserting elements to the list
   myList.push_back(1);
   myList.push_back(2);
   myList.push_back(3);
   //Size of the list after inserting elements
   cout<<"Size of the list after inserting elements: "<<myList.size();
   return 0;
}

Output

If we run the above code then it will generate the following output

Size of the list : 0
Size of the list after inserting elements: 3
raja
Published on 26-Feb-2020 11:58:05
Advertisements