views:

377

answers:

5
#include <array>

template <typename T>
class Vector4<T> {
    std::array<T, 4> _a; // or 'T _a[4];'?
};

template <typename T>
class Matrix4<T> {
    std::array<T, 16> _a; // or 'T _a[16];'?
    //Vector4<T> row0; // or should i use this instead
    //Vector4<T> row1; // it makes other code easier but how
    //Vector4<T> row2; // can i implement something like 
    //Vector4<T> row3; // std::array::data()?
};

thanks

edit: ya its for 3d game programming... so i will need more then boost matrix can provide anyway like rotate and translate and invert etc...

A: 

I don't think you would want std::array _a[4], as you will create 4 arrays with that.

Brammie
A: 

There's already a standard std::vector class. If you need something specifically for linear algebra, I'd suggest looking into boost ublas.

Charles Salvia
vector allocates data on heap by default, not a good choice for a small size data object like fixed-size vector/matrices.
Marcus Lindblom
+4  A: 

The way you want to do it, would be

std::vector<std::vector<int> > my_matrix(4, std::vector<int>(4));

However, I would rather use ublas from boost if you want to handle matricies:

#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>

int main () {
    using namespace boost::numeric::ublas;
    matrix<double> m (3, 3);
    for (unsigned i = 0; i < m.size1 (); ++ i)
        for (unsigned j = 0; j < m.size2 (); ++ j)
            m (i, j) = 3 * i + j;
    std::cout << m << std::endl;
}

The example is from their website http://www.boost.org/doc/libs/1%5F40%5F0/libs/numeric/ublas/doc/matrix.htm

Tristram Gräbener
I wouldn't recommend using dynamically allocated matrices when he is only interested in 4x4 matrices...
Inverse
Indeed, the compiler will be able to optimize much better if it knows the size of the matrices it's working on at compile-time. I'd use a `std::/boost::array`.
GMan
A: 

Boost ublas is a great library, but is not optimized if all you want to is 4-D stuff. I would recommend keeping the two classes independent:

template <typename T>
class Vector4<T> {
    T _a[4];
};

template <typename T>
class Matrix4<T> {
    T _m[4][4];
};

You can always cast a pointer to a row (_m[i]) into a Vector4<> if needed. To get a column vector though you will need an adapter class like ublas uses.

Inverse
Why not makes the matrix out of an array of vector instead of casting ?
Matthieu M.
i would like to know too... also the nvidia sdk matrix class uses T _m[16] instead of T _m[4][4]
rakkarage
+3  A: 

I've found Eigen to be the most straightforward of the C++ linear algebra libraries, and it contains templates for fixed and variable dimension vectors and matrices. Like Boost, it's a pure template "library" so there are no libs to build / include, but I find it to be more complete and significantly more performant than Boost's ublas.

scotchi