簡體   English   中英

填充2D陣列

[英]Populating 2D-Array

  • 嗨,我正嘗試在C ++中創建一個數組,專門用用戶輸入填充2D數組,然后將其按升序和降序排列。
  • 因此,其中一些可能是由我的一個朋友提供的,而其余的都是我創建的,我不確定自己做錯了什么。
  • 我已經能夠輸出一個靜態生成的數組,但是不能與用戶的輸入一起存儲。

-對我來說,代碼有意義,但是我不知道如何將用戶輸入存儲到數組中,有人可以幫助/強調一下嗎? 由於我不確定如何填充2D數組或對C ++很有信心。

int main ()
{

    int array[6][5];
    int i, j, swapx, swapy;

    printf("Initial array \n");
    for (i = 0; i < N; i++)
    {
        printf ("{%d, %d}", array[0][i], array [1][i]);
        if(i != (N - 1)){
            printf(", ");
        }
    }

    for (i = 0; i < (N - 1); i++)
    {
        for (j = 0; j < (N - i - 1); j++)
        {
            if(array[0][j] > array[0][j+1]){
                swapx = array[0][j];
                swapy = array[1][j];
                array[0][j] = array[0][j+1];
                array[1][j] = array[1][j+1];
                array[0][j+i] = swapx;
                array[1][j+1] = swapy;
            }
        }
    }

    printf("\nSorted Array: \n");
    for (i = 0; i < N; i++)
    {
        printf ("{%d, %d}", array[0][i], array [1][i]);
        if(i != (N - 1)){
            printf(", ");
        }
    }
}

您必須遍歷2D數組的每一行,然后遍歷每一列,並使用std::cin通過輸入設置列值。

#include <iostream>
#include <string>

int main()
{
    int arr[2][2];
    std::cout << "Enter four values: ";

    //loop through each row
    for (auto& row : arr) {
        //loop through each column
        for (auto& col : row) {
            std::cin >> col;
            //obtain input
        }
    }

    for (auto& row : arr) {
        for (auto& col : row) {
            std::cout << col << ' ';
        }
        std::cout << std::endl;
    }

    //do what you want with the array
}

暫無
暫無

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

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