Find length of an array in C++ in 5 different ways

In this post, we will discuss how to find length of an array in C++.


 

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

 

1. Template argument deduction

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++, the recommended solution is template argument deduction as shown below:

 

Download   Run Code

 

2. C++11 – std::distance

Since C++11, we can use std::distance which takes iterators to the beginning and the end of an array and returns the number of hops between the two.

 

Download   Run Code

 

3. Using pointer arithmetic

Before C++11, we can use pointer arithmetic to do the same as shown below.

 

Download   Run Code

 

4. C++17 – std::size()

C++17 introduced the templated function std::size() in the <iterator> header which returns the number of elements in the given container or C-array.

 

Run Code

 

5. Using boost C++ library

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

 

Download   Run Code

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Leave a Reply

avatar
  Subscribe  
Notify of