My goal is to print out object[] array using a for-each loop. My output is a string of addresses. I've tried subscripting but that defeats the purpose of a range-base for().
#include<iostream>
#include<array>
usingnamespace std;
struct Elements
{
int x;
int y;
};
int main()
{
int object[52];
for (int x = 0; x<4; ++x)
{
for (int y = 0; y<12; ++y)
{
object[y] = y;
}
}
int ctr = 0;
for(auto &elem:object)
{
std::cout<<object;
}
return 0;
}
I misread the question at first, thought it was supposed to be an array of Elements which follows a similar style, but there is some added fun in getting it to work.
Your latest code is working. You might want to add some whitespace such as ' ' or '\t' or '\n' to the cout statement.
The garbage values are because the array is not properly initialised.
int object[52] = { 0 }; // set array to all zeros.
std::cout<<elem << ' '; // output a space between values
It might be working but the code above is a mess. I corrected the array initialization, and the loop to create an array with 12 repeating elements x 4. I've been looking after the "elem" answer for quite a while. Now it makes sense. This also shows that for-each() loops can count through normal arrays. Though I wonder how far you can take it:instead of subscripted array could you also use a for-each loop with a pointer based array.