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
}
```

Then I can allocate it with

```
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;
}
```

Now do I do the equiv in C++?

EDIT:

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

This answer has 20 upvotes now, but it is **not intended as an endorsement of std::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.

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.

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:

- 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.

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
```

Licensed under: CC-BY-SA with attribution

Not affiliated with: Stack Overflow