1

Suppose I have a structure bbox containing 6 sets, where each set contains 4 vectors. I can add a vector element by using bbox.set1.vect1.push_back(foo). However, I'm reading data from a file and I'm looking for an elegant way to store the data in the vectors. Using a double for() loop with indices i (1 to 6) and k (1 to 4) I've tried the following (using string concatenation):

string test1 = "bbox.set";
string test2 = ".vect";
string fin = test1 + to_string(i) + test2 + to_string(k);
fin.push_back(val);

Though the code compiles fine, nothing seems to happen. Explicitly writing bbox.set1.vect1.push_back(foo) does work. Can this be done in such a way? In another topic I've read that C does not support changing/creating variable names during runtime, but here I simply try to access an existing variable.

Knippie
  • 83
  • 2
  • 7
  • 1
    What type does val have? – Klemens Morgenstern May 06 '15 at 23:43
  • Perhaps I should have mentioned that val is a double – Knippie May 06 '15 at 23:45
  • That can't be done trivially; it requires most of a compiler and enough information from the compilation of the main code for whatever function translates the string into a call to `bbox.set1.vect1.push_back(foo)`. Decidedly non-trivial; decidedly non-standard. Not undoable; debuggers translate strings typed at them into function calls. But outside a debugger, it's kinda hard... – Jonathan Leffler May 06 '15 at 23:49

2 Answers2

6

No, C++ does not support this, since variable names are resolved at compile time, which means that by the time the program runs, the variable names themselves are meaningless. (In other words, the name bbox has in practice been replaced by a set of numbers representing the object called by that variable name.)

If you really need to something like this, you should consider using a container such as std::map, which you can use to map strings to objects. You can't access them like variables, though, but you can dynamically build strings to decide which object to get.

Frxstrem
  • 38,761
  • 9
  • 79
  • 119
  • All right, I think I'd rather use a double switch than the map container (which seems quite complicated). But thanks for your quick reply! – Knippie May 07 '15 at 00:03
2

What you are looking for is some method of reflection, which C++ does not natively support. There is no way to do what you want directly.

Instead you will need to provide your own support.

Guvante
  • 18,775
  • 1
  • 33
  • 64