Correct way of looping through C++ arrays
In C/C++ sizeof
. always gives the number of bytes in the entire object, and arrays are treated as one object. Note: sizeof
a pointer--to the first element of an array or to a single object--gives the size of the pointer, not the object(s) pointed to. Either way, sizeof
does not give the number of elements in the array (its length). To get the length, you need to divide by the size of each element. eg.,
for( unsigned int a = 0; a < sizeof(texts)/sizeof(texts[0]); a = a + 1 )
As for doing it the C++11 way, the best way to do it is probably
for(const string &text : texts)
cout << "value of text: " << text << endl;
This lets the compiler figure out how many iterations you need.
EDIT: as others have pointed out, std::array
is preferred in C++11 over raw arrays; however, none of the other answers addressed why sizeof
is failing the way it is, so I still think this is the better answer.
string texts[] = {"Apple", "Banana", "Orange"};
for( unsigned int a = 0; a < sizeof(texts); a = a + 1 )
{
cout << "value of a: " << texts[a] << endl;
}
Nope. Totally a wrong way of iterating through an array. sizeof(texts)
is not equal to the number of elements in the array!
The modern, C++11 ways would be to:
- use
std::array
if you want an array whose size is known at compile-time; or - use
std::vector
if its size depends on runtime
Then use range-for when iterating.
#include <iostream>
#include <array>
int main() {
std::array<std::string, 3> texts = {"Apple", "Banana", "Orange"};
// ^ An array of 3 elements with the type std::string
for(const auto& text : texts) { // Range-for!
std::cout << text << std::endl;
}
}
Live example
You may ask, how is std::array
better than the ol' C array? The answer is that it has the additional safety and features of other standard library containers, mostly closely resembling std::vector
. Further, The answer is that it doesn't have the quirks of decaying to pointers and thus losing type information, which, once you lose the original array type, you can't use range-for or std::begin/end
on it.
sizeof
tells you the size of a thing, not the number of elements in it. A more C++11 way to do what you are doing would be:
#include <array>
#include <string>
#include <iostream>
int main()
{
std::array<std::string, 3> texts { "Apple", "Banana", "Orange" };
for (auto& text : texts) {
std::cout << text << '\n';
}
return 0;
}
ideone demo: http://ideone.com/6xmSrn