The following code goes through each voter in an election and allows them to rank their candidates by preference: 1, 2, 3 etc.
The code works but I'm just attempting to understand what happens when assigning one int to a 2d array of int
s, preferences[voter][rank] = i
.
What happens when you assign a single int to a 2 dimensional array of int
s?
// Keep querying for votes
for (int i = 0; i < voter_count; i++)
{
// Query for each rank
for (int j = 0; j < candidate_count; j++)
{
string name = get_string("Rank %i: ", j + 1);
// Record vote, unless it's invalid
if (!vote(i, j, name))
{
printf("Invalid vote.\n");
return 4;
}
}
printf("\n");
}
//first loop through ranks gets input from the user... this loop through compares the users
//response to each of the candidates, then locks them in as that rank for that voter
bool vote(int voter, int rank, string name)
{
for (int i = 0; i < candidate_count; i++)
{
if(strcmp(name, candidates[i].name) == 0)
{
preferences[voter][rank] = i;
return true;
}
}
return false;
}
In your code
preferences[voter][rank] = i;
does not assign an int
to a "2 dimensional array of int
s" as you mentioned.
Here, preferences[voter][rank]
is one element in the array, of type int
, and you're assigning an integer value to it.
To elaboate, an array defined like
int arrayofints[10] = {0};
has 10 elements, of type int
, accessed by arrayofints[i]
, where 0 <= i <= 9
. So a statement like
for (int i = 0; i< 10; i++){
arrayofints[i] = i;
}
access arrayofints[0]
, arrayofints[1]
.... respectively and store the value of i
into that element. Same goes for multi-dimensional arrays.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.