具有数组或向量的多维数组的实现 [英] implementation of multi-dimensional array with an array or vector

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

问题描述

我想使用单个数组或向量来实现多维数组,可以像通常的多维数组一样访问它(例如: a [1] [2] [3] )。
我遇到的问题是如何实现 [] 运算符。如果数组的维数为1,则a [1]应该返回位于索引1处的元素。但是,如果维数大于1,该怎么办?在嵌套向量的情况下,例如3维向量, vec [1] 将返回 vector< vector<某些类型>。 >



我尝试实现自己的多维数组的原因是,我在编译时不知道数组的维数。尺寸实际上取决于某些条件。实际上,数组的最大维数是3,因此我可以定义三个不同的向量,但是我个人认为这不是正确的选择。

解决方案

operator [] 只能接受单个参数。



最好的解决方案是使用<而是code> operator()。



如果您绝对要使用 operator [] ,则可以让它返回特定于维度的类型的代理对象,在该对象上可以再次应用 operator [] ,依此类推。 / p>




这是一个常见问题,在C ++常见问题解答“如何为Matrix类创建下标运算符?” (链接指向main FAQ的英文版。)



在询问之前先咨询FAQ通常是个好主意。





I want to implement multi-dimensional array using single array or vector, which can be accessed like usual multi-dimensional array(ex: a[1][2][3]). Where I am stuck at is how to implement [ ] operator. If the dimension of an array is 1, then a[1] should return the element which is located at index 1. But what if the dimension is more than one? In case of nested vector,say 3-dimensinal vector, vec[1] will return vector<vector<some type> >.

The reason why I am trying to implement my own multi-dimensional array is that I don't know the dimension of an array at compile time. The dimension really depends on some conditions. Actually maximum dimension of an array is 3, so I can define three different vectors, but I personally don't think this is the right choice.

解决方案

operator[] can only take a single argument.

The best solution is to use operator() instead.

If you absolutely want to use operator[] then you can let it return a proxy object, of a type specific to the dimension, on which operator[] can be applied again, and so on.


This is a Frequently Asked Question, and is answered in the C++ FAQ’s “How do I create a subscript operator for a Matrix class?” (the link is to main English version of the FAQ).

It's often a good idea to consult the FAQ before asking.


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

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