C++ - 使用 'i' 检查 for 循环中的不同变量

C++ - Using 'i' to check different variables in a for loop

本文关键字:变量 循环 检查 使用 C++ for      更新时间:2023-10-16

我不确定该怎么称呼它,所以我也不确定要搜索什么,但是有没有办法在 for 循环中使用"i"作为变量名称的一部分?顺便说一下,使用C++。

例如

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?
}

我感谢任何意见。

谢谢。

使用数组

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

疯狂解决方案部门:

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

也可以工作,但当然不像使用数组那么容易。

如果您使用的是C++则应从C++标准库中选取其中一个容器,如[std::array] 1 或 [std::vector] 2。

例:

#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;
}