C++ Standard Library C++ STL Library

C++ <list> - size() Function



The C++ list::size function is used to find out the total number of elements in the list.

Syntax

size_type size() const;
size_type size() const noexcept;

Parameters

No parameter is required.

Return Value

Number of elements present in the list.

Time Complexity

Constant i.e, Θ(1)

Example:

In the example below, the list::size function is used find out the total number of elements in a list called MyList.

#include <iostream>
#include <list>
using namespace std;
 
int main (){
  list<int> MyList{10, 20, 30, 40, 50};

  cout<<"List size is: "<<MyList.size()<<"\n";

  cout<<"Three elements are added in the List.\n";
  MyList.push_back(60);
  MyList.push_back(70);
  MyList.push_back(80);

  cout<<"Now, List size is: "<<MyList.size()<<"\n";
  
  return 0;
}

The output of the above code will be:

List size is: 5
Three elements are added in the List.
Now, List size is: 8

❮ C++ <list> Library