C ++ - using 'i' to test various variables in a for loop

I'm not sure how to call it, so I'm also not sure what to look for, but is there a way to use "i" as part of a variable name in a for loop? By the way, using C ++.

For example,

int int1, int2, int3;
for(int i = 1; i<=3; i++){
     //somehow use i as inti or int+i, etc.
     //I was wondering if this is possible?
}

      

I appreciate any input.

Thank.

+3


source to share


3 answers


use an array



int ints [3];
for(int i = 0; i<3; i++){
     int x = ints[i];
}

      

+16


source


Crazy Decisions Department:

int int1, int2, int3;
int *arr[3] = { &int1, &int2, &int3 };
for(int i = 1; i<=3; i++){
   ... *arr[i] ... 
}

      



would also work, but not as easy as using an array of course.

+6


source


If you are using C ++ you should choose one of the containers from the C ++ standard library like [std::array]

1 or [std::vector]

2 .

Example:

#include <array>
#include <iostream>

int main() {

  std::array<int, 3> const ia = {{ 2, 4, 8 }};

  for( int i : ia ) {
    std::cout << "[" << i << "] ";
  }
  std::cout << std::endl;

  return 0;
}

      

+2


source







All Articles