How to find out the length of an array?

2019-06-05 23:55发布

问题:

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

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

回答1:

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.



回答2:

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.



回答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


回答4:

Like this:

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


标签: c++ arrays size