This post will discuss how to find the length of an array in C++.

In the previous post, we have seen how to find the length of an array in C using the sizeof operator and pointer arithmetic. This post provides an overview of some of the available alternatives to accomplish this in C++.

1. Using template function

We know that an array decays into a pointer when passed to a function as an argument. To get the length of an array inside a function in C++, we can use template argument deduction which works with different types of arguments, by using a placeholder for the type. We can write a template function that can find the length of any array as follows:

Download  Run Code

 
The template function takes an array of any type and size as a reference parameter, and returns the size of the array. The size of the array is deduced by the compiler from the array argument.

2. Using std::distance function

Since C++11, we can use std::distance, which takes iterators at the beginning and the end of an array, and returns the total number of hops between the two. For example, we can find the length of an array of integers as follows:

Download  Run Code

3. Using pointer arithmetic

We can also use the pointer arithmetic to find the length of an array with the std::begin and std::end functions. These functions are a part of the <iterator> header file, and they return iterators to the beginning and the end of a container or an array. To find the length of an array, we can subtract the iterator to the beginning from the iterator to the end. For example:

Download  Run Code

4. Using std::size function

C++17 introduced the template function std::size() which returns the total number of elements in a container or an array. This function is a part of the <iterator> header file, and can be used as follows:

Download  Run Code

5. Using boost C++ Library

Another good alternative is to use the boost::size (or boost::distance) to get length of an array. It is preferable to use boost::size() over boost::distance().

Download Code

That’s all about finding the length of an array in C++.