Computer Science Canada

[C++] Iterating Over Arrays

Author:  wtd [ Sat Mar 27, 2004 1:28 am ]
Post subject:  [C++] Iterating Over Arrays

When iterating over arrays in C++, it's tempting to use something along the lines of:

code:
int length_of_array = 10;
int my_array[length_of_array];

// now, let's populate the array with values

for (int i = 0; i < length_of_array; i++)
   my_array[i] = i * 2;


There's nothing technically incorrect with this, but there's another method which fits better with standard practice as seen in the Standard Template Library.

code:
int length_of_array = 10;
int my_array[length_of_array];
int * beginning of_array = my_array;
int * end_of_array = my_array + 10;

// now, let's populate the array with values

for (int * iterator = beginning of_array; iterator != end_of_array; iterator++)
   *iterator = iterator - my_array;


: