简体   繁体   English

填充2D阵列

[英]Populating 2D-Array

  • Hi, i am trying to create an array in C++ specifically to populate a 2D-Array with the user input and then order it into Ascending and Descending. 嗨,我正尝试在C ++中创建一个数组,专门用用户输入填充2D数组,然后将其按升序和降序排列。
  • So some of this could was given by a fellow friend whilst the rest i created, i am not sure what i am doing wrong.. 因此,其中一些可能是由我的一个朋友提供的,而其余的都是我创建的,我不确定自己做错了什么。
  • I have been able to output a statically generated Array but not been able to store with the input from the user. 我已经能够输出一个静态生成的数组,但是不能与用户的输入一起存储。

- To me the code makes sense but i do not know how to store the user input into the array, Could anyone help/emphasize a bit? -对我来说,代码有意义,但是我不知道如何将用户输入存储到数组中,有人可以帮助/强调一下吗? Since i am not sure how to populate the 2D array or greatly confident on C++. 由于我不确定如何填充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(", ");
        }
    }
}

You have to loop through each row and then column of the 2D array and use std::cin to set the columns values via input. 您必须遍历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