std::string array[] = { "one", "two", "three" };
How do I find out the length of the array
in code?
std::string array[] = { "one", "two", "three" };
How do I find out the length of the array
in code?
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
.
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.
C++11 provides std::extent
which gives you the number of elements along the N
th dimension of an array. By default, N
is 0, so it gives you the length of the array:
std::extent<decltype(array)>::value
Like this:
int size = sizeof(array)/sizeof(array[0])