[英]Populating 2D-Array
-對我來說,代碼有意義,但是我不知道如何將用戶輸入存儲到數組中,有人可以幫助/強調一下嗎? 由於我不確定如何填充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.