list size() function in C++ STL

C++Server Side ProgrammingProgramming

In this article we will be discussing the working, syntax and examples of list::size() 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::size()?

list::size() is an inbuilt function in C++ STL which is declared in <list> header file. size() returns the size of a particular list container. In other words it returns the number of elements which are present in a list container.

Syntax

list_container.size()

This function accepts no parameter.

Return Value

This function returns a size_type value i.e.number of elements in a list_container.

Example

In the below code we are calculating the size of the integer list which is the number of elements it contains using the function size().

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   //Create a list
   list<int> myList;
   //insert elements to the List
   myList.push_back(23);
   myList.push_back(12);
   myList.push_back(21);
   int size = myList.size();
   cout << "size of the list is : "<<size;
   return 0;
}

Output

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

size of the list is : 3
raja
Published on 02-Mar-2020 08:13:37
Advertisements