使用指针算术的最大2d数组值



我试图写一个程序,以找到在列中初始化5x5矩阵的最大值,并将其更改为-1。我找到了做这件事的方法,但我还想找到一个更好的解决办法。

输入:

double array2d[5][5];
double *ptr;
ptr = array2d[0];
//        initializing matrix
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 5; ++j) {
if (j % 2 != 0) {
array2d[i][j] = (i + 1) - 2.5;
} else {
array2d[i][j] = 2 * (i + 1) + 0.5;
}
}
}

这是我对第一列的解决方案:

//        Changing the matrix using pointer arithmetic
for (int i = 0; i < (sizeof(array2d) / sizeof(array2d[0][0])); ++i) {
if (i % 5 == 0) {
if (maxTemp <= *(ptr + i)) {
maxTemp = *(ptr + i);
}
}
}
for (int i = 0; i < (sizeof(array2d) / sizeof(array2d[0][0])); ++i) {
if (i % 5 == 0) {
if (*(ptr + i) == maxTemp) {
*(ptr + i) = -1;
}
}
}

我可以重复这个代码5次,并得到结果,但我想要一个更好的解决方案。THX .

下面是使用指针运算的完整程序。这个程序将替换2D数组-1中每列的所有最大值。

#include <iostream>
int main()
{
double array2d[5][5];
double *ptr;
ptr = array2d[0];
//        initializing matrix
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 5; ++j) {
if (j % 2 != 0) {
array2d[i][j] = (i + 1) - 2.5;
} else {
array2d[i][j] = 2 * (i + 1) + 0.5;
}
}
}
//these(from this point on) are the things that i have added.
//Everything above this comment is the same as your code.  
double (*rowBegin)[5]  = std::begin(array2d);
double (*rowEnd)[5] = std::end(array2d);
while(rowBegin != rowEnd)
{
double *colBegin = std::begin(rowBegin[0]);
double *colEnd = std::end(rowBegin[0]);

double lowestvalue = *colBegin;//for comparing elements
//double *pointerToMaxValue = colBegin;

while(colBegin!= colEnd)
{
if(*colBegin > lowestvalue)
{
lowestvalue = *colBegin;
//pointerToMaxValue = colBegin ;
}
colBegin = colBegin + 1;
}
double *newcolBegin = std::begin(rowBegin[0]);
double *newcolEnd = std::end(rowBegin[0]);
while(newcolBegin!=newcolEnd)
{
if(*newcolBegin == lowestvalue)
{
*newcolBegin = -1;  
}
++newcolBegin;
}
++rowBegin;
}
return 0;
}

程序可以在这里查看。

您可以添加print out of the array的所有元素来检查上面的程序是否用-1替换了每列中所有的最大值。

我用java写的,但我想你能理解。这个是同时处理所有5列的。你可以试试:

int count = 0;
double max = 0;
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 5; ++j) {
if (j == 0) {
max = array2d[j][I];
count = 0;
}
if (array2d[j][i] > max) {
count = j;
}
}
array2d[count][i] = -1;
}

最新更新