C++ - 使用 'i' 检查 for 循环中的不同变量
C++ - Using 'i' to check different variables in a for loop
我不确定该怎么称呼它,所以我也不确定要搜索什么,但是有没有办法在 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;
}
相关文章:
- 在循环中按顺序遍历成员变量
- 我可以创建一个包含两个变量的 for 循环,但时间复杂度仍然为 O(n) 吗?
- 与 for 循环中的变量混淆
- 如何在循环之外重新输入变量
- 如何使用将字符串拆分为 for 循环中的变量的程序
- 在变量声明中使用 for 循环
- C++ 和 Boost.Python - 如何将变量公开给 python 并在循环中更新它?
- C++ Code 在 for 循环期间不会累积变量中的总和,仅提供最终迭代值
- C++ 在循环中添加计数器变量并再次初始化其值
- (C++)虽然循环一次不起作用,但我引入了多个变量
- 如何添加循环期间分配的变量?
- C++,每个循环初始化一个新的静态变量
- 在 for 循环中更新两个变量时遇到问题C++
- 循环中的变量被设置为下一个数组的元素始终具有相同的内存地址?
- 需要循环帮助以迭代方式添加到程序集中的总和变量
- 在 c++ 中基于范围的 for 循环中使用引用作为控制变量
- 如何在循环中动态创建变量(c++)
- 变量循环范围会导致返回局部变量的地址引用
- ifstream变量循环不打印任何内容
- c++变量/循环问题