1

I want to create a for loop that will fill a bunch of arrays with data in c++. Now to save space and in the future once more arrays are added which they will, I have the for loop. Each array for demonstration purposes is called Array# (# being a number) The point of the for loop would be to set a constant with maximum arrays, then cycle through each array filling by appending i to the end of the Array name.

For example in pseudo code:

for (i = 1; i < numberofarrays; i++)  
{ fill (Array & i) with ("Array" & i & "-default.txt")}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294

2 Answers2

8

It is impossible to generate Variable Names by any type of code.
(Meaning it is impossible to generate dynamic variable names on Runtime or on Compiletime)

The best solution possible would be a array of arrays:

int Arrays[][];

Calling Arrays[0] would give you the first array.

If you want to determine the number of arrays during Runtime you need to use pointers!

That would look like that:

(int[])* Arrays = new (int[])[numberofarrays];

Accessing the arrays in the array would work the same!

An alternative would be using the container vector from std.

The code would the look like this:

#include<vector>

// More includes

// Optional
using namespace std;

// Somewhere in your code
vector<vector<int>> Arrays;

You still would acces the elements by using your standard array method (Arrays[15][78] e.g.)

BrainStone
  • 3,028
  • 6
  • 32
  • 59
1

You don't really need the name. You can use an std::vector of arrays. This will not work out of the box, see Correct way to work with vector of arrays

Another approach would be to have an std::map of arrays. You could have the name as the key, if that is what you really want. You will still have to use the same workaround as before to have an array as a value. See Character Array as a value in C++ map for example.

Community
  • 1
  • 1
Vadim
  • 2,847
  • 15
  • 18