gpt4 book ai didi

c++ - 将列添加到二维数组

转载 作者:行者123 更新时间:2023-11-30 03:19:47 31 4
gpt4 key购买 nike

用户输入任何所需的array,代码查找每一列,如果任何列中的任何元素等于数字y。那么代码应该添加一个新的零列在它前面。

Code

#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] 但徒劳无功。

最佳答案

你需要更换

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 而不是普通指针,以避免像此处那样您忘记释放内存的错误。

关于c++ - 将列添加到二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53393872/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com