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

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

NPS
  • 5,625
  • 8
  • 49
  • 84

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
  • 216,937
  • 30
  • 383
  • 461
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
  • 12,737
  • 3
  • 26
  • 38
  • 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
  • 104,685
  • 19
  • 232
  • 315
2

Like this:

int size = sizeof(array)/sizeof(array[0])
Peter R
  • 2,667
  • 15
  • 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