For example, I have an array with 3 elements
int array [] = {1, 4, 66};
How can I know how many elements array
contains?
For example, I have an array with 3 elements
int array [] = {1, 4, 66};
How can I know how many elements array
contains?
Do this with:
std::size(myarray);
std::size
is in <iterator>
.
Some sources will tell you to use a "trick" like sizeof(myarray)/sizeof(myarray[0])
. But this is error-prone. The name of an array decays really easily to a pointer, for which this "trick" gives the wrong result. std::size
will either work, or break the build.
Plus, when you switch from C arrays to std::array
, it'll still work!
You can use sizeof(myarray)/sizeof(int)
.
But you really should start using std::array
, which does the same thing as your array and is safer. And comes with a size()
method.