在c++中更改数组值

change array value in c++

本文关键字:数组 c++      更新时间:2023-10-16

在我的cpp程序中有一个二维数组,它在八列三行中存储双精度值。我有一个函数来确定每行的最小值。现在我想改变这个最小变量的值。我通过指针传递数组,这对我来说是一个挑战。下面是获取最小值的getMaxMin()。如有任何帮助,不胜感激。

 double **getMaxMin(double **scores){
    for(int i=0;i<3;i++){
        double small=scores[i][0];
        for(int j=1;j<8;j++){
            if(small>scores[i][j]){
                small=scores[i][j];
            }
        }
        cout<<small<<endl;
    }
    return scores;
}

保存small时也保存索引:

// ...
if( small > scores[i][j] )
{
    small = scores[i][j];
    small_i = i;
    small_j = j;
}

// later
scores[small_i][small_j] = //...

我猜对于这个场景,您只需要存储列索引,因为您是逐行执行的。这是一个更通用的版本。

    int smalli,smallj;
....
      if(small>scores[i][j]){
                small=scores[i][j];
                smalli = i;
                smallj = j;
           }
    ...
    scores[smalli][smallj] = newval;

这回答你的问题了吗?

 double **getMaxMin(double **scores){
    for(int i=0;i<3;i++){
        double small=scores[i][0];
        int best_j = 0; // NEW
        for(int j=1;j<8;j++){
            if(small>scores[i][j]){
                small=scores[i][j];
                best_j = j; // NEW
            }
        }
        cout<<small<<endl;
        scores[i][best_j] = 42.0f; // NEW
    }
    return scores;
}

我可能遗漏了一些东西,但是为什么要使用最小的地址并使用它来分配新值呢?

(注:我可能错过了一些东西,没有在愤怒中编写c++…) )

double **getMaxMin(double **scores)
{
    for(int i=0;i<3;i++){
        double* small = &scores[i][0];
        for(int j=1;j<8;j++){
            if(*small>scores[i][j]){
                small=&scores[i][j];
            }
        }
        cout<<*small<<endl;
    }
    *small = 100.0; // Set new value here
    return scores;
}

有很多方法可以做到这一点,但最简单的方法就是保存索引。

跟踪每行的最小值:

double **getMaxMin(double **scores){
    for(int i=0;i<3;i++){
        double small=scores[i][0];
        int small_j = 0;
        for(int j=1;j<8;j++){
            if(small>scores[i][j]){
                small=scores[i][j];
                small_j = j;
            }
        }
        cout<<small<<endl;
        // Now you can change the value of the smallest variable for that row
        //small[i][small_j] = yourvalue
    }
    return scores;
}

跟踪整个数组中的最小值:

double **getMaxMin(double **scores){
    for(int i=0;i<3;i++){
        double small=scores[i][0];
        int small_j = 0;
        int small_i = 0;
        for(int j=1;j<8;j++){
            if(small>scores[i][j]){
                small=scores[i][j];
                small_j = j;
                small_i = i;
            }
        }
        cout<<small<<endl;
    }
    // Now you can do something with the smallest value in the entire array
    // small[small_i][small_j] = yourvalue
    return scores;
}