C++ List::size() Function



The C++ std::list::size() function is used to retrieve the number of elements in the list.

The size of the list is nothing but just the total count of the number of elements present in the current list. If the list is an empty list, this function returns zero as the list size, but in case the list is empty but contains some white spaces, the size() function counts all the white spaces as one(1) and returns it as the size of the current list.

Syntax

Following is the syntax of the C++ std::list::size() function −

int size() const;

Parameters

  • It does not accept any parameter.

Return Value

This function the number of elements in the container.

Example 1

If the list is a non-empty list, this function returns the number of elements in the list.

In the following program, we are using the C++ std::list::size() function to retrieve the size of the current list {1, 2, 3, 4, 5}.

#include<iostream>
#include<list>
using namespace std;

int main() {
   //create a list
   list<int> num_list = {1, 2, 3, 4, 5};
   cout<<"The list elements are: "<<endl;
   for(int l : num_list){
      cout<<l<<" ";
   }
   cout<<"\nThe size of list: "<<num_list.size()<<endl;
}

Output

On executing the above program, it will produce the following output −

The list elements are: 
1 2 3 4 5 
The size of list: 5

Example 2

If the list is an empty list, this function returns zero.

Following is another example of the C++ std::list::size() function. Here, we are creating a list(type char) named empt_list with an empty value. Then, using the size() function, we are trying to retrieve the size of the current list.

#include<iostream>
#include<list>
using namespace std;

int main() {
   //create a list
   list<char> empt_list = {};
   cout<<"The list elements are: ";
   for(char l : empt_list){
      cout<<l<<" ";
   }
   cout<<"\nThe size of list: "<<empt_list.size()<<endl;
}

Output

Following is the output of the above program −

The list elements are: 
The size of list: 0

Example 3

If the list(type string) is empty but contains white spaces, the size() function returns the list size as 1.

In this example, we are creating a list(type string) named names with an empty value {" "}. Using the size() function, we are trying to get the size of this list.

#include<iostream>
#include<list>
using namespace std;

int main() {
   //create a list
   list<string> names = {" "};
   cout<<"The list elements are: ";
   for(string l : names){
      cout<<l<<" ";
   }
   cout<<"\nThe size of list: "<<names.size()<<endl;
}

Output

The above program produces the following output −

The list elements are:   
The size of list: 1