How to use Template Function In C++
We can use a template function to find the size of an array.
C++ program to Find the Size of an Array Using Template Function
C++
// C++ program to find size of // an array using Template Function #include <bits/stdc++.h> using namespace std; // Calculating size of an array template < typename T, size_t N> int array_size(T (&arr)[N]) { return N; } int main() { int arr[] = { 1, 2, 3, 4, 5, 6 }; int size = array_size(arr); cout << "Number of elements in arr[] is " << size; return 0; } // This code is contributed by Susobhan Akhuli |
Number of elements in arr[] is 6
Explanation
The array_size() function is a template function that takes two parameters:
- T: Type of array elements
- N: Size of the array
The parameter T (&arr)[N] means the function accepts a reference to any type and any size of array. When array_size function is called with the array name as parameter, T is deduced as int and N is deduced as 6.
Complexity Analysis
- Time complexity: O(1)
- Auxiliary space: O(1)
How to Find Size of an Array in C++ Without Using sizeof() Operator?
In C++, generally, we use the sizeof() operator to find the size of arrays. But there are also some other ways using which we can find the size of an array. In this article, we will discuss some methods to determine the array size in C++ without using sizeof() operator.