array::size() in C++ STL with Example

C++ STL array::size() function with example: Here, we are going to learn about a library function "size()" of "array" class, which is used to return the total number of elements/size of an array.
Submitted by IncludeHelp, on November 10, 2018

"array" is a container which is used to create/container which is used to create/contains the fixed size arrays, the "array" in C++ STL is "class" actually and they are more efficient, lightweight and very easy to use, understand, "array" class contains many inbuilt functions, thus the implementation of the operations are fast by using this rather that C-Style arrays.

To use "array" class and its function, we need to include "array" class and its function, we need to include "array" header.

array::size() function

"size()" function returns the size of the array (Note: "size()" can also be used for other containers like list etc).

Syntax:

    array_name.size();

Parameters:

There is no parameter to be passed.

Return type:

Returns size of the array


Example:

    Input:
    arr1{} //an empty array
    arr2{10,20,30} //array with 3 elements
    
    Function calls:
    arr1.size()
    arr2.size()
    
    Output:
    Size of arr1: 0
    Size of arr2: 3

Program:

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

int main() {
	//declaring two arrays 
	array<int,0> arr1{};        //an empty array 
	array<int,5> arr2{};        //array size: 5, elements 0
	array<int,5> arr3{10, 20, 30};      //array size: 5, elements: 3
	array<int,5> arr4{10, 20, 30, 40, 50}; //array size:5, elements: 5


	cout<<"size of arr1: "<<arr1.size()<<endl;
	cout<<"size of arr2: "<<arr2.size()<<endl;
	cout<<"size of arr3: "<<arr3.size()<<endl;
	cout<<"size of arr4: "<<arr4.size()<<endl;

	return 0;
}

Output

size of arr1: 0
size of arr2: 5
size of arr3: 5
size of arr4: 5



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.