Warm tip: This article is reproduced from serverfault.com, please click

其他-矩阵条件不输出结果C ++

(其他 - Matrix condition not outputting result C++)

发布于 2020-11-29 13:05:24

对于包含整个矩阵的最小数目的每一列,我想用最小数目完全替换该列。

例如:

input
8 3 3 7         
2 1 6 1             
8 1 3 1             
9 1 7 1         

///////

output
8 1 3 1 
2 1 6 1 
8 1 3 1 
9 1 7 1 

我想到了这个主意:

step 1: find minimum
step 2: create a bool variable and make it false (so active=false)
step 3: go through every column and check if it has the minimum number, if it does -> restart the loop 
and make the bool variable true (so active=true). If active==true, replace the column with the minimum number

这是我写的代码:

int main(){
    int i, j, n=4, m=4, v[101][101];
    for(i=0; i<n; i++){
        for(j=0; j<m; j++){
            cin>>v[i][j];
        }
    }
    int minv=1000000000;
    for(i=0; i<n; i++){
        for(j=0; j<m; j++){
            if(v[i][j]<minv){
                minv=v[i][j];
            }
        }
    }
    bool active=false;
    for(j=0; j<m; j++){
        for(i=0; i<n; i++){
            if(v[i][j]==minv){
                i=0;
                active=true;
            }
            if(active){
                v[i][j]=minv;
            }
        }
    }
    for(i=0; i<n; i++){
        for(j=0; j<m; j++){
            cout<<v[i][j]<<" ";
        }
        cout<<endl;
    }
}

我的问题是编译器不输出任何内容。我认为这是

for(j=0; j<m; j++){
        for(i=0; i<n; i++){
            if(v[i][j]==minv){
                i=0;
                active=true;
            }
            if(active){
                v[i][j]=minv;
            }
        }
    }

一段代码。你们能帮帮我吗?

Questioner
dr 21
Viewed
0
670k 2020-11-30 13:05:43

你询问了C ++中的解决方案。你倾向于使用更多C实践的静态数组。我采取了自由的态度,将你的代码重写为更具C ++性质的解决方案。

#include <iostream>
#include <vector>

int main()
{
    std::vector<std::vector<int>> v = {
        {8, 3, 3, 7},
        {2, 1, 6, 1},
        {8, 1, 3, 1},
        {9, 1, 7, 1}};
    std::vector<int> min_row;
    int minv = v[0][0];
    //Here we find min value of matrix
    for (auto i : v)
        for (auto j : i)
            if (j < minv)
                minv = j;
    //Here we find columns that hold min value
    for (auto i : v)
        for (size_t j = 0; j < i.size(); j++)
            if (i.at(j) == minv)
                min_row.push_back(j);
    //After looping trough columns that has
    //min values we change all values to min
    for (auto j : min_row)
        //Notice here we used reference so we could actually change the value
        for (auto &i : v)
            i.at(j) = minv;
    //Here we just print out our matrix
    for (auto i : v)
    {
        for (auto j : i)
            std::cout << j << " ";
        std::cout << std::endl;
    }
    return 0;
}