繁体   English   中英

从文件中读取2D数组并将其传递给另一个函数

[英]Reading 2D array from a file and passing it to another function

我用C ++编写了这段代码,以从文件中读取2D数组。 现在,我想用函数更好地组织代码。 我遇到的问题是我无法弄清楚如何将加载到内存的2D数组传递给同一程序中的另一个函数。 这是我需要组织成函数的代码:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

#define M 4
#define N 4

int main(){
    int i, j;
    float A[M][N];
    string line;
    ifstream matrix("matrix.txt");
    if (matrix.is_open())
    {
        do
        {
            for(i=0; i<M; i++) 
            {
                for(j=0; j<N; j++) 
                    matrix >> A[i][j];
            }
        }
        while (getline(matrix,line));
        matrix.close();
    }
    else cout << "Unable to open file";

    float sumline[M]={0};                       

    for(i=0;i<M;i++)
    {
        for(j=0;j<N;j++)
            sumline[i]+=A[i][j];            
    }

    float sumcolumn[N]={0};                     

    for(j=0;j<N;j++)
    {
        for(i=0;i<M;i++)
            sumcolumn[j]+=A[i][j];      
    }


    for (i=0; i<M; i++){                    
        for (j=0; j<N; j++){                
            if(sumline[i]<sumcolumn[j]){    
                cout << "Error, total sum of column "<<j<<" is greater than the sum of the line"<<i<<endl;
                return 0;                   
            }
        }
    }

    int mincol=sumcolumn[0];                

    for (i=0; i<N; i++){                    
        if(mincol>sumcolumn[i])
            mincol==sumcolumn[i];
    }
    float avgline = 0.0;
    for (i=0; i<M; i++){
        avgline=avgline+sumline[i];
    }
    avgline = avgline/M;

    if (avgline * 3 > mincol) {
        cout << "Conditions verified"<<endl;
        }
    else{
        cout << "Error, triple of the avg of line is less than the lowest sum of column"<<endl;
        return 0;       
        }

    return 0;
}

该代码基本上在2D数组上进行一些数学运算。 我还想保持尽可能简单,即使using namespace std;也不using namespace std; 这不是真正的好习惯,或者我从文件中读取数组的方式真的很基本,我需要这样。 非常感谢。

代替使用c数组

float A[M][N];

您可以改用

using MyArrayType = std::array<std::array<float>, M>, N>;
MyArrayType A;

现在您可以按引用传递( MyArrayType&const MyArrayType&

话虽如此:ac数组可以像更困难的语法一样传递: (float (&a)[M][N]); -强烈建议尽可能使用std::array

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM