Divide an array into multiple arrays

Jan 16, 2015 at 1:09am
Hey guys,

I am trying to do this:

Read a text file which is like:

2
2 10 1 2 7
3 8 3 7 7 10 7

The first line indicates how many paths exist in my design.
The second and third lines are those lines(the first number indicates 2 pairs, so 10,1 and 2,7 are 2 pairs)
The first element in the third line indicates 3 pairs and the pairs are 8,3 and 7,7 and 10,7.

I have been able to read the text file and store these into ONE array. However, I need to divide them up and have each line in a seperate array.

So for example

array alpha to contain 10,1 and 2,7
array beta to contain 8,3 and 7,7, and 10,7

How would you do this?
Cheers :)
Jan 16, 2015 at 2:05am
Are you familiar with structures?
http://www.cplusplus.com/doc/tutorial/structures/
It is possible to have arrays that hold structures.

Are you also familiar with dynamic memory?
http://www.cplusplus.com/doc/tutorial/dynamic/
Seeing that your text file gives you the size of your arrays, you could dynamically allocate them.
Jan 16, 2015 at 2:47am
Is it possible to create multiple arrays based on the input in the first line? So for example if the user enteres 2, I create 2 arrays and put each line into each array. For instance:

User enters 3
Next lines are:
1 2 3 4
5 6 7 8
9 0 1 2

and create 3 arrays based on this
Array Alpha contains 1 2 3 4
Array Beta contains 5 6 7 8
Array Gama contains 9 0 1 2
Jan 16, 2015 at 2:58am
It sounds like you need vectors. Vectors are an easy way to represent jagged arrays. Jagged arrays are arrays of arrays with different sizes.
http://en.wikipedia.org/wiki/Jagged_array

You can create a vector of vector of ints like this:
1
2
3
4
5
6
7
8
9
10
std::vector< std::vector<int> > arrays; //the space between > and > is important
//otherwise c++ will be confused without the space
arrays.push_back(std::vector<int>()); //pushes a new empty int vector
arrays[0].push_back(1); //pushes the number 1 on to the first vector/row
arrays[0].push_back(2);
arrays[0].push_back(3); //now the first row has the numbers 1, 2, and 3
arrays.push_back(std::vector<int>(5, 0)); //pushes a new int vector containing five zeroes
arrays[1][2] = 6; //overwrite the third zero with a six in the second vector/row
//notice how I did not have to use push_back for the last example
//because the new array already had 5 spots in it 
Last edited on Jan 16, 2015 at 3:00am
Jan 16, 2015 at 10:47pm
Thank you! That's exactly what I needed :)
Topic archived. No new replies allowed.