将列添加到二维数组

时间:2018-11-20 13:17:28

标签: c++ arrays visual-c++ multidimensional-array jagged-arrays

如果用户输入了任何需要的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],但徒劳。

1 个答案:

答案 0 :(得分:2)

您需要替换

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";
    }
}

使用

for (int i = 0; i < rows; i++) {
    for (int j = 0; j < columns; j++) {
        std::cout << array[i][j] << " ";
        if (arrx[j]) {
           std::cout << 0 << " ";
         }
    }
}

这会在每个列值被标记的元素之后打印零。您试图做的是逐列打印到标准输出,这不是它的工作原理。

我还敦促您考虑使用std :: vector而不是普通指针,以避免出现类似此处忘记分配内存的错误。