This shows the information for both arrays coming from the same source file. Can I use data from separate sources, say from a function and from user input? How do you code this?
Asked another way, what part of this code makes these arrays parallel? What happens in line 2?
I'm wanting to understand this better- thanks for the help.
//A clearer example of parallel arrays
constint N = 10;
string names[N];
char grades[N];
//fill names and grades with data
for( int i = 0; i < N; ++i )
cout << names[i] << "'s grade is " << grades[i] << endl;
/*
* The idea here is that for any given index in [0,N)
* both names[index] and grades[index] will correspond to the same student.
*/
Thats it. So, the variables can be from any source(s), a file, a function return, whatever. What relates them is that we increment and output them at the same time, as in the cout statement in the for loop. A parallel array isn't a formal structure, like a for loop, or array function. Its created whenever we use any two related arrays in synchronization. Do the arrays have to be the same size?
Yes. The whole point of a parallel arrays is that:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
string names[N];
int age[N];
double height[N];
//if these arrays are parallel it means
names[i]
age[i]
height[i]
//all refer to a different aspect of the same person
assert(i != j);
//where as
names[j]
age[j]
height[j]
//all refer to a different person
struct Person {
string name;
int age;
double height;
};
Person people[N];
//now
Person p1 = people[i];
//represents a person object, and
p1.name //is there name, and etc. with
p1.age
p1.weight