C++ vector: declaring multiple variables with name

2019-09-20 07:03发布

问题:

I am up to upgrade a program to make it dynamically configurable from files. What i need is a number of vector viables, and that number being dependant of int variable.

int k=4 //loaded from file, i handled it

vector<string> NAME(k)

Moreover, names of those variables need to be rising numbers (first object: NAME1, second NAME2 etc.).

This is my first ever post there, so sorry for all the mistakes or lack of information :)

回答1:

You can't dynamically name variables, but you could store them in a map.

std::map<std::string, std::vector<std::string> > myVectors;

for (int i = 0; i < k; ++i)
{
  std::ostringstream name;
  name << "NAME" << i;

  myVectors.insert(std::make_pair(name.str(), std::vector<std::string>()));
}


回答2:

Use

vector<vector<string> > name(k);

Where do you get the names from? I from file you could map instead. Probably yes when reading again sorry. Did not solve more than part of the problem.