In the code below I can print members of elem (.x .y). How do I print the index number (for lack of better words)of elem itself (similar to index of a normal matrix)?
But would have to always count up to the desired value. For example if I wanted to access members of elem 100, elem.x & elem.y, I would have to set up a loop. In other words my thinking that you can pluck a value out like an array is wrong.
I looked over a lot of suggested documentation. I have down what to do with my_array but don't understand why you can access elem members but not the index to it itself.
Take a minute and think about why this is OP. The variable 'elem' isn't an array, it's a reference to an element in 'my_array'. Think about why that is different.
I didn't know elem wasn't an array. Foolish to try to index it.
Seems like the elem and my_array have some overlapping functions despite one being a reference element to the array and the other being an array element. If I use my_array[i].x and my_array[i].y they are the same results as elem.x and elem.y. In the output the elem and my_array seem to be pairing data(overlap). I could use some disambiguation here on when to use one versus the other.
They are identical by design. The ranged-based for loop iterates over your array, giving you the items out of it. Similarly, going through the valid indices of an array and passing them to the subscript operator will give you the items out of it.
You should use whichever one makes more sense.
If you only want the items of the array (which I would wager a guess is the usual case), then use a range-based for loop. This also has the advantage of working for various other kinds of ranges that don't necessarily use the numeric subscript method.
1 2 3 4
for(auto elem : container) {
// use elem
// I don't need to care about the details of iterating container
}
If you need a counter for some other reason (perhaps you want to number a list or something), then you can declare a counter and do it that way.
1 2 3 4 5
for(unsignedint i = 0; i < container.size(); ++i) {
auto elem = container[i];
// now operate on elem
// Note that here I have to know how to calculate the size of container, and also figure out how to access elements out of it.
}