1
std::string array[] = { "one", "two", "three" };

How do I find out the length of the array in code?

NPS
  • 6,003
  • 11
  • 53
  • 90

4 Answers4

6

You can use std::begin and std::end, if you have C++11 support.:

int len = std::end(array)-std::begin(array); 
// or std::distance(std::begin(array, std::end(array));

Alternatively, you write your own template function:

template< class T, size_t N >
size_t size( const T (&)[N] )
{
  return N;
}

size_t len = size(array);

This would work in C++03. If you were to use it in C++11, it would be worth making it a constexpr.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
4

Use the sizeof()-operator like in

int size = sizeof(array) / sizeof(array[0]);

or better, use std::vector because it offers std::vector::size().

int myints[] = {16,2,77,29};
std::vector<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );

Here is the doc. Consider the range-based example.

bash.d
  • 13,029
  • 3
  • 29
  • 42
  • Is it possible to define an `std::vector` with initializaiton (like in my example with ordinary array)? – NPS Apr 07 '13 at 10:04
  • 1
    C++11 offeres initializers. Otherwise you can create an array as you did and assign it to the std::vector. Ill post the doc in a minute – bash.d Apr 07 '13 at 10:09
  • This C level expression should not be recommended without explaining [its type unsafety and how that can be remedied](http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c/7439261#7439261). – Cheers and hth. - Alf Apr 07 '13 at 10:12
3

C++11 provides std::extent which gives you the number of elements along the Nth dimension of an array. By default, N is 0, so it gives you the length of the array:

std::extent<decltype(array)>::value
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
2

Like this:

int size = sizeof(array)/sizeof(array[0])
Peter R
  • 2,865
  • 18
  • 19
  • I knew this one but I thought it might not work with `std::string` (due to variable text lengths). – NPS Apr 07 '13 at 10:02
  • 2
    This C level expression should not be recommended without explaining [its type unsafety and how that can be remedied](http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c/7439261#7439261). – Cheers and hth. - Alf Apr 07 '13 at 10:18
  • @NPS `sizeof(std::string)` is always the same ; it does not have anything to do with how many characters are stored in the string – M.M Sep 27 '14 at 03:44