The array::size() method is used to find the number of elements in the array container. It is the member method std::array class defined inside <array> header file. In this article, we will learn about the array::size() method in C++.
Example:
// C++ Program to illustrate the use of array::size()
#include <bits/stdc++.h>
using namespace std;
int main() {
array<int, 3> a = {1, 2, 3};
cout << a.size();
return 0;
}
Output
3
array::size() Syntax
a.size();
Parameters
- This function does not require any parameter.
Return Value
- Returns the number of elements present in the array.
- If the array is empty, it returns 0.
Note: As std::arrays are fixed size containers whose size is set at the time of declaration, the array::size() method will always return the same size for the container instance.
More Examples of array::size()
The following examples demonstrates the use of array::size() function in different scenarios:
Example 1: Find the Size of Array of Strings
// C++ Program to find the size of array of
// strings using array::size()
#include <bits/stdc++.h>
using namespace std;
int main() {
array<string, 3> a = {"Geeks", "For",
"Geeks"};
// Finding the size
cout << a.size();
return 0;
}
Output
3
Time Complexity: O(1)
Auxiliary Space: O(1)
Example 2: Using array::size() on an Uninitialized Array
// C++ Program to find the size of uninitialized
// array using array::size() method
#include <bits/stdc++.h>
using namespace std;
int main() {
array<int, 3> a;
// Finding the size
cout << a.size();
return 0;
}
Output
3
Time Complexity: O(1)
Auxiliary Space: O(1)
Example 3: Using array::size() on an Array with Initial Size 0.
// C++ Program to implement array::size() method
#include <bits/stdc++.h>
using namespace std;
int main() {
array<int, 0> a;
// find the size of an array using array::size()
cout << a.size();
return 0;
}
Output
0
Time Complexity: O(1)
Auxiliary Space: O(1)