n维向量 [英] n-dimensional vector

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

问题描述

假设我要声明一个向量的向量,该向量是a ...(最多n个维度)的向量.

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

像这样:

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;

是否可以通过模板元编程对任意n执行此操作?

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

推荐答案

是的,而且非常简单.

很像归纳证明,我们建立了一个递归案例和一个(部分专门的)基本案例来结束递归.

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;

这篇关于n维向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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