简体   繁体   English

将矩阵作为函数指针传递

[英]Passing Matrix as pointer to function

In my project I've these files:在我的项目中,我有这些文件:

functions.h
functions.cc
main.cc

I'm trying to pass Matrix to functions as pointers in this way:我试图以这种方式将 Matrix 作为指针传递给函数:

main.cc主文件

// Size -> const short Size = 10;
int mtr1[Size][Size];
matrix_insert((int *)mtr1);

functions.h函数.h

void matrix_insert(int *mtr);

functions.cc函数.cc

void matrix_insert(int *mtr) {
  short i, j;

  for (i = 0; i < Size; i++) {
    for (j = 0; j < Size; j++) {
      std::cin >> *(mtr + i * Size + j);
    }
  }
}

This is actually working but I don't like this way...这实际上是有效的,但我不喜欢这种方式......
Is there a better method?有没有更好的方法?

Thanks!谢谢!

EDIT: Is possible to emulate matrix with vector?编辑:可以用向量模拟矩阵吗?

If you really want to use C arrays, then you can do it as follows:如果你真的想使用 C 数组,那么你可以这样做:

main.cc主文件

int mtr1[Size][Size];
matrix_insert(mtr1);

functions.h函数.h

const short Size = 10;
void matrix_insert(int mtr[Size][Size]);

functions.cc函数.cc

void matrix_insert(int mtr[Size][Size]) {
  short i, j;

  for (i = 0; i < Size; i++) {
    for (j = 0; j < Size; j++) {
      std::cin >> mtr[i][j];
    }
  }
}

Working version: http://ideone.com/1ik7T9工作版本: http : //ideone.com/1ik7T9

Create a matrix class like this one:创建一个像这样的矩阵类:

http://www.parashift.com/c++-faq/matrix-subscript-op.html http://www.parashift.com/c++-faq/matrix-subscript-op.html

You can do this using templates:您可以使用模板执行此操作:

template<int Size>
void matrix_insert(int (&mtr)[Size][Size])
{
    short i, j;

    for (i = 0; i < Size; i++)
    {
        for (j = 0; j < Size; j++)
        {
            std::cin >> mtr[i][j];
        }
    }
}

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

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