Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

n-dimensional vector

Tags:

c++

templates

Let's say I want to declare a vector of a vector of a vector of a... (up to n dimensions).

Like so:

using namespace std;
// for n=2
vector<vector<int> > v2;
// for n=3
vector<vector<vector<int> > > v3;
// for n=4
vector<vector<vector<vector<int> > > > v3;

Is there a way to go about doing this for an arbitrary n with template metaprogramming?

like image 952
Yktula Avatar asked Oct 28 '12 00:10

Yktula


People also ask

What does N dimensional mean?

Adjective. n-dimensional (not comparable) (mathematics) Having an arbitrary number of dimensions.

Is N dimensional vector space?

It is a fundamental theorem of linear algebra that the number of elements in any basis in a finite dimensional space is the same as in any other basis. This number n is the basis independent dimension of V; we include it into the designation of the vector space: V(n,F).

What is N dimensional spaces?

To be specific, Definition: A space is just a set where the elements are called points. and. Definition: N dimensional space (or Rn for short) is just the space where the points are n-tuplets of real numbers.

What is a basis for an N dimensional vector space?

If V is a vector space of dimension n, then: A subset of V with n elements is a basis if and only if it is linearly independent. A subset of V with n elements is a basis if and only if it is a spanning set of V.


1 Answers

Yes, and it's pretty straightforward.

Much like a proof by induction, we set up a recursive case and a (partially specialized) base case that ends the recursion.

template<size_t dimcount, typename T>
struct multidimensional_vector
{
    typedef std::vector< typename multidimensional_vector<dimcount-1, T>::type > type;
};

template<typename T>
struct multidimensional_vector<0,T>
{
    typedef T type;
};

multidimensional_vector<1, int>::type v;
multidimensional_vector<2, int>::type v2;
multidimensional_vector<3, int>::type v3;
multidimensional_vector<4, int>::type v4;
like image 118
Ben Voigt Avatar answered Oct 24 '22 03:10

Ben Voigt