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

查看:275
本文介绍了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<double> .其他一些人建议的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天全站免登陆