[英]What happens when we assign one int to an array of 2 ints?
The following code goes through each voter in an election and allows them to rank their candidates by preference: 1, 2, 3 etc.以下代码通过选举中的每个选民,并允许他们按偏好对候选人进行排名:1、2、3 等。
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
.该代码有效,但我只是想了解将一个 int 分配给int
的二维数组时会发生什么, preferences[voter][rank] = i
。
What happens when you assign a single int to a 2 dimensional array of int
s?当您将单个 int 分配给int
的二维数组时会发生什么?
// 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.如您所述,不会将int
分配给“ int
s 的二维数组”。
Here, preferences[voter][rank]
is one element in the array, of type int
, and you're assigning an integer value to it.在这里, preferences[voter][rank]
是数组中的一个元素,类型为int
,您正在为其分配一个 integer 值。
To elaboate, an array defined like详细地说,一个数组定义为
int arrayofints[10] = {0};
has 10 elements, of type int
, accessed by arrayofints[i]
, where 0 <= i <= 9
.有 10 个int
类型的元素,由arrayofints[i]
访问,其中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.分别访问arrayofints[0]
, arrayofints[1]
.... 并将i
的值存储到该元素中。 Same goes for multi-dimensional arrays.多维 arrays 也是如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.