For循环中的数组?

时间:2013-03-23 12:43:10

标签: c++ arrays 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;
  }
}

1 个答案:

答案 0 :(得分:5)

将我的评论扩展为答案。

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