For循环中的数组

Array in For loop?

本文关键字:数组 循环 For      更新时间:2023-10-16

让我们以下面的代码为例:我想使用字符串"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
  }
}