【发布时间】:2019-04-22 05:10:33
【问题描述】:
用户输入所需的 rows 和 columns 的所需数组。代码需要查看数组并找到至少有一个负数的所有行。如果找到,则代码会在已创建的行下方添加新的 zeros 行。
代码
#include <pch.h>
#include <iostream>
using namespace std;
int main()
{
int rows, columns;
std::cout << "Enter the number of rows: ";
std::cin >> rows;
std::cout << "Enter the number of columns: ";
std::cin >> columns;
int **array = new int*[rows]; //Generating a 2-D array
for (int i = 0; i < rows; i++)
array[i] = new int[columns];
std::cout << "Enter the elements" << std::endl;
for (int i = 0; i < columns; i++) //loop for input array
for (int j = 0; j < rows; j++) //elements
std::cin >> array[i][j];
for (int i = 0; i < columns; i++) { //print the array
for (int j = 0; j < rows; j++) {
std::cout << array[i][j] << " ";
}
std::cout << "\n";
}
for (int i = 0; i < columns; i++) { //finding rows with negative
for (int j = 0; j < rows; j++) { //numbers and adding a new
if (array[i] < 0) { // row of zeros below
array[i + 1][j] = 0;
std::cout << array[i][j] << " ";
}
}
std::cout << "\n";
}
return 0;
}
例如
如果我们输入一个数组,如1 1 1 1 1
2 -2 2 -2 2
3 3 3 3 3
4 -4 -4 4 4
5 5 5 5 5
答案应该是1 1 1 1 1
2 -2 2 -2 2
0 0 0 0 0 -----> new rows added
3 3 3 3 3
4 -4 -4 4 4 ------> new rows added
0 0 0 0 0
5 5 5 5 5
但是我的代码没有这样做?
【问题讨论】:
-
您的阵列尺寸不适合接受这一点。你可以使用向量的向量吗?
-
不,我们还没有进入向量。这个问题需要以某种方式解决。
-
@Damien 这是什么意思,我的数组还没有尺寸?
-
@J.Doe 您将需要为新行分配,为指针数组重新分配,然后在指针数组中执行一些内存移动以将其插入正确的位置。如果你应该学习 c++,那么这不应该手动完成,而是使用
std::vector。如果不允许你使用它,那么我会说老师应该教 C 而不是 C++。 -
行数增加。您需要对数组进行超维。此外,添加新行时必须增加
row。
标签: c++ arrays c++11 multidimensional-array jagged-arrays