簡體   English   中英

當我們將一個 int 分配給一個由 2 個 int 組成的數組時會發生什么?

[英]What happens when we assign one int to an array of 2 ints?

以下代碼通過選舉中的每個選民,並允許他們按偏好對候選人進行排名:1、2、3 等。

該代碼有效,但我只是想了解將一個 int 分配給int的二維數組時會發生什么, preferences[voter][rank] = i

當您將單個 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;
}

在您的代碼中

 preferences[voter][rank] = i;

如您所述,不會int分配給“ int s 的二維數組”。

在這里, preferences[voter][rank]是數組中的一個元素,類型為int ,您正在為其分配一個 integer 值。

詳細地說,一個數組定義為

 int arrayofints[10] = {0};

有 10 個int類型的元素,由arrayofints[i]訪問,其中0 <= i <= 9 所以像這樣的聲明

 for (int i = 0; i< 10; i++){
     arrayofints[i] = i;
  }

分別訪問arrayofints[0]arrayofints[1] .... 並將i的值存儲到該元素中。 多維 arrays 也是如此。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM