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

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

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Or std::extent<decltype(array)>::value.
@sftrabbit I hadn't even thought of that one. Nice!
@sftrabbit Make that an answer and get my +1
Your len is missing a constexpr :)
@DanielFrey good point, but I wanted to provide a C++03 option. I will add a note about that.
|
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.

3 Comments

Is it possible to define an std::vector with initializaiton (like in my example with ordinary array)?
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
This C level expression should not be recommended without explaining its type unsafety and how that can be remedied.
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

3 Comments

Does it do all the calculations at compile time (i.e. after compilation it's just a number, needing no extra calculations)?
@NPS: yes, you can see that from the fact that it's a type
Any way to make it short (like macro but I'd rather not use macros)?
2

Like this:

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

3 Comments

I knew this one but I thought it might not work with std::string (due to variable text lengths).
This C level expression should not be recommended without explaining its type unsafety and how that can be remedied.
@NPS sizeof(std::string) is always the same ; it does not have anything to do with how many characters are stored in the string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.