C++ 矩阵类 [英] C++ Matrix Class

查看:37
本文介绍了C++ 矩阵类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C 中,如果我想创建一个矩阵结构,我会使用:

In C, if I wanted to create a matrix struct, I would use:

struct matrix {
  int col, row;
  double data[1]; // I want the matrix entries stored
                  // right after this struct
}

然后我可以分配它

matrix* allocate_matrix(int row, int col) {
  matrix* m = malloc(sizeof(matrix) + sizeof(double) * (row * col - 1));
  m->row = row; m->col = col;
  return m;
}

现在我可以用 C++ 做等价的吗?

Now do I do the equiv in C++?

我想知道在 C++ 中实现矩阵类的规范方式.

I want to know the cannonical way to implement a matrix class in C++.

推荐答案

nota bene.

这个答案现在有 20 个赞成票,但它并不打算作为对 std::valarray 的认可.

nota bene.

This answer has 20 upvotes now, but it is not intended as an endorsement of std::valarray.

根据我的经验,最好花时间安装和学习使用成熟的数学库,例如 Eigen.与竞争对手相比,Valarray 的功能较少,但效率并不高,也不是特别容易使用.

In my experience, time is better spent installing and learning to use a full-fledged math library such as Eigen. Valarray has fewer features than the competition, but it isn't more efficient or particularly easier to use.

如果您只需要一点线性代数,并且您坚决反对向工具链添加任何内容,那么也许 valarray 会适合.但是,无法表达问题的数学正确解决方案是一个非常糟糕的境地.数学是无情和无情的.使用适合工作的工具.

If you only need a little bit of linear algebra, and you are dead-set against adding anything to your toolchain, then maybe valarray would fit. But, being stuck unable to express the mathematically correct solution to your problem is a very bad position to be in. Math is relentless and unforgiving. Use the right tool for the job.

标准库提供了std::valarray.std::vector<>,由这里的一些其他人建议,旨在作为对象的通用容器.valarray,鲜为人知,因为它更专业(不使用specialized"作为 C++ 术语),有几个优点:

The standard library provides std::valarray<double>. std::vector<>, suggested by a few others here, is intended as a general-purpose container for objects. valarray, lesser known because it is more specialized (not using "specialized" as the C++ term), has several advantages:

  • 它不会分配额外的空间.vector 在分配时向上舍入到最接近的 2 次幂,因此您可以调整其大小而无需每次都重新分配.(您仍然可以调整 valarray 的大小;它仍然与 realloc() 一样昂贵.)
  • 您可以将其切片以轻松访问行和列.
  • 算术运算符按您的预期工作.
  • It does not allocate extra space. A vector rounds up to the nearest power of two when allocating, so you can resize it without reallocating every time. (You can still resize a valarray; it's just still as expensive as realloc().)
  • You may slice it to access rows and columns easily.
  • Arithmetic operators work as you would expect.

当然,与使用 C 相比的优势在于您不需要管理内存.维度可以位于堆栈中,也可以位于切片对象中.

Of course, the advantage over using C is that you don't need to manage memory. The dimensions can reside on the stack, or in a slice object.

std::valarray<double> matrix( row * col ); // no more, no less, than a matrix
matrix[ std::slice( 2, col, row ) ] = pi; // set third column to pi
matrix[ std::slice( 3*row, row, 1 ) ] = e; // set fourth row to e

这篇关于C++ 矩阵类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆