【发布时间】:2019-04-22 22:45:55
【问题描述】:
用户输入任何想要的array,代码查找每一列,如果任何列中的任何元素等于数字y。那么代码应该在它前面添加一个new column of zeros。
代码
#include <pch.h>
#include <iostream>
using namespace std;
int main()
{
int y, rows, columns;
std::cout << "Enter the number of rows: ";
std::cin >> rows;
std::cout << "Enter the number of columns: ";
std::cin >> columns;
std::cout << "Enter a number Y: ";
std::cin >> y;
//-----------------------Generating 2-D array---------------------------------------------------------
int **array = new int*[2 * rows];
for (int i = 0; i < rows; i++)
array[i] = new int[columns];
//------------------------Generating bool--------------------------------------------------------------
bool *arrx = new bool[columns];
//-----------------------Input Array Elements---------------------------------------------------------
std::cout << "Enter the elements" << std::endl;
for (int i = 0; i < columns; i++)
for (int j = 0; j < rows; j++)
std::cin >> array[i][j];
//--------------------Loop for the array output--------------------------------------------------------
for (int i = 0; i < columns; i++) {
for (int j = 0; j < rows; j++) {
std::cout << array[i][j] << " ";
}
std::cout << "\n";
}
//-------------------Loop for finding columns with even numbers----------------------------------------
for (int i = 0; i < columns; i++) {
arrx[i] = false;
for (int j = 0; j < rows; j++) {
if (array[j][i] == y) {
arrx[i] = true;
}
}
}
std::cout << "\n";
//--------------------Loop for addition of new columns infront of even numbers--------------------------
for (int i = 0; i < columns; i++) {
for (int j = 0; j < rows; j++) {
std::cout << array[i][j] << " ";
}
std::cout << "\n";
if (arrx[i]) {
for (int i = 0; i < rows; i++) {
std::cout << 0 << " ";
}
std::cout << "\n";
}
}
return 0;
}
这里的代码只向 array 添加行,而我需要添加 columns 。我曾尝试将array[i][j] 更改为array[j][i],但没有成功。
【问题讨论】:
-
您不使用
std::vector的任何特殊原因? -
因为这是我们课程中添加和删除元素的最后一项手动任务。我们要开始的下一个主题是
std::vector -
请在问题中添加此类要求。家庭作业通常带有相当奇怪的约束,例如在现实生活中,没有理智的 C++ 编码人员会为该任务使用手动分配的数组
标签: c++ arrays visual-c++ multidimensional-array jagged-arrays