For循环中的数组
Array in For loop?
让我们以下面的代码为例:我想使用字符串"name"作为我在for循环中使用的数组的名称,但我收到字符串"array"。如何使用这个字符串的名称我的数组?
#include <iostream>
#include <string>
using namespace std;
int main() {
int array[3];
array[0] = 1;
array[1] = 2;
array[2] = 3;
string name = "array";
int i;
for (i = 0; i < 3; i++) {
cout << name[i] << endl;
}
}
将我的评论扩展为一个答案。
c++没有反射:没有一种通用的方法可以使用包含其标识符的字符串来引用变量(或其他任何东西)。
但是,有一些数据结构可用于基于键(如字符串)检索数据。在您的情况下,您可以这样做:#include <iostream>
#include <map>
#include <string>
#include <vector>
int main() {
std::map<std::string, std::vector<int> > allArrays; // mapping strings to vectors of ints
allArrays["array"].push_back(1); // fill vector stored under key "array"
allArrays["array"].push_back(2);
allArrays["array"].push_back(3);
// another way:
std::vector<int> &vec = allArrays["another_array"];
vec.push_back(-1);
vec.push_back(-2);
vec.push_back(-3);
std::string name = "array";
for (size_t i = 0; i < allArrays[name].size(); ++i) {
std::cout << allArrays[name][i] << 'n'; //not using endl - no need to flush after every line
}
}
相关文章:
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 使用for循环检查数组中的重复项
- 并行用于C++17中数组索引范围内的循环
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 在C++中,建议通过数组循环的方式是什么?
- 如何制作不允许重复值的 C++ int 数组循环?
- 数组 - 循环遍历辅助阵列
- 数组循环没有输出
- C++ 数组循环的时间复杂度
- 数组循环结构
- 更现代的C++数组循环方式
- 数组循环在循环结束后输出垃圾
- C++数组循环问题仍然需要帮助
- 动态数组 循环问题的元素计数器
- 平均值的C++数组循环
- c++数组循环问题
- C++ 我的数组/循环有什么问题?
- c++数组循环
- 数组循环不工作
- 从向量数组循环中获取数据以供以后使用