2014-04-23 36 views
0

我要声明为以下代码是从文本文件读出的矩阵的函数。代码可以在下面看到。C++函数上执行操作和声明函数

if (infile == "A.txt") 
    { 
     ifstream myfile("A.txt"); 
    string line; 
    int MatA[3][3]; 
    int i=0; 
    while (getline (myfile, line)) 
    { 
     stringstream ss(line); 
     for(int j=0; j<3; j++) 
      ss >> MatA[i][j]; // load the i-th line in the j-th row of mat 
     i++; 
    } 
    // display the loaded matrix          
     for(int i=0; i<3; i++) 
      { 
       for(int j=0; j<3; j++) 
      cout<<MatA[i][j]<<" "; 
      cout<<endl; 
      } 

     } 

现在我所试图做的就是声明这个矩阵的功能,所以当我在后面的代码执行操作我就可以调用该函数,而不是重新写整个矩阵。但是我很难做到这一点,我已经做出的将矩阵作为函数声明的尝试可以在下面看到。

int display (int MatA) 
{ 
    for(int i=0; i<3; i++) 
    { 
     for(int j=0; j<3; j++) 
      cout<<MatA[i][j]<<" "; 
     cout<<endl; 
    } 
} 

但是,出现错误说[i]'表达式必须有一个指向对象类型的指针'。

如果有人能帮助那简直太好了!

+0

您正在传递一个'int',而对于二维阵列应该能够传送一个'INT **' – SingerOfTheFall

回答

1

例如,该功能可以被定义如下方式

const size_t N = 3; 

void display(const int (&MatA)[N][N]) 
{ 
    for (size_t i = 0; i < N; i++) 
    { 
     for (size_t j = 0; j < N; j++) std::cout << MatA[i][j] << " "; 
     std::cout << std::endl; 
    } 
} 

另一种方法是下面

const size_t N = 3; 

void display(const int (*MatA)[N], size_t n) 
{ 
    for (size_t i = 0; i < n; i++) 
    { 
     for (size_t j = 0; j < N; j++) std::cout << MatA[i][j] << " "; 
     std::cout << std::endl; 
    } 
} 

的功能可以被称为

#include <iostream> 

const size_t N = 3; 

// the function definitions 

int main() 
{ 
    int a[N][N] = {}; 
    // some code to fill the matrix 

    display(a); 
    display(a, N); 
} 

,最后你可以用的帖子评论中建议的方法@boycy虽然至于我,我不喜欢这种做法。 例如

#include <iostream> 

const size_t N = 3; 

void display(const int **MatA, size_t m, size_t n) 
{ 
    for (size_t i = 0; i < m * n; i++) 
    { 
     std::cout << MatA[i] << " "; 
     if ((i + 1) % n == 0) std::cout << std::endl; 
    } 
} 

int main() 
{ 
    int a[N][N] = {}; 
    // some code to fill the matrix 

    display(reinterpret_cast<const int **>(a), N, N); 
} 
+0

两种这些实现的并不如通用,因为他们可以/应当[按理说]是;第一个迫使矩阵是一个平方NxN,而第二个迫使它是nxN。 @SingerOfTheFall建议将矩阵作为int **传递是最灵活的(也是最常用的)方法。因此 函数签名将'空隙显示器(const int的** MATA,为size_t米,为size_t n)的'和访问'MATA [i] [j]''用于在i''[0,M)'和' '[0,n]中的j'将按照需要工作。 – boycy

+0

@boycy在这种情况下,您可能不会将二维数组传递给此函数而不更改函数的主体。作者没有询问通用函数的定义。如果在使用模板函数或容器时需要通用方法。 –

+0

我的歉意,你当然是对的。直到我已经忘记了多维数组如何不愉快的是C++ :-) 这是值得的注意,模板上的阵列尺寸的功能将正常工作,但因为模板是为每一个独特的(M,N)实例化一次配对,它可能会导致到臃肿的二进制文件。 – boycy

0

你传递一个int MatA到显示器,但你要int[][]作为参数。然而,这不起作用。所以你必须通过int**并对其执行指针算术,否则你将不得不为这个矩阵创建一个更好的访问器。

我建议考虑看看像OpenCV Mat类型,解决您的问题类似的实现。