我希望能够在 c++ 中的堆上定义一个通用的多维数组,并且我想为数组分配一个连续的内存以快速访问元素(而不是锯齿状的向量向量)。这是我的实现
#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;
typedef vector<unsigned int> VUI;
class Invalid_MDArray : public exception{
public:
char* what(){
return "Array cannot be constructed ";
}
};
template <class T>
class MArray{
private:
VUI dsize;
VUI cumsize;
T* p;
unsigned int stot;
public:
unsigned int size(){ return stot; }
unsigned int size(unsigned int i) { return dsize[i]; }
MArray(const VUI& a){
stot = 1;
for (unsigned int i = 0; i<a.size(); i++){
if (a[i] == 0) {
Invalid_MDArray o;
throw o;
}
stot = stot*a[i];
dsize.push_back(a[i]);
cumsize.push_back(stot);
}
dsize.push_back(stot);
p = new T[stot];
}
~MArray(){
delete[] p;
}
inline T& operator()(VUI&& a){
if (a.size() != dsize.size() - 1) {
out_of_range o("Index is out of bound!");
throw o;
}
unsigned int i = 0;
while (i<a.size()){
if (a[i]>dsize[i] - 1) {
out_of_range o("Index is out of bound!");
throw o;
}
i++;
}
unsigned int index = 0;
// index=i+imax*j+imax*jmax*k
i = 0;
while (i<a.size()){
if (i == 0) {
index = a[i];
}
else {
index = index + a[i] * cumsize[i - 1];
}
i++;
}
return p[index];
}
};
int main(){
try{
MArray<int> t({ 2, 2, 2 });
t({ 1, 1, 1 }) = 10;
cout << t({ 1, 1, 1 }) << endl;
// I prefer accessing the elements like this -> cout<<t(1,1,1)<<endl;
MArray<int> tt({ 2, 0, 2 }); // OOPS! cannot construct this array!
cout << t.size()<<endl;
t({ 1, 2, 1 }) = 1000; //OOPS! outofbound exception!
}
catch (exception &e){
cout << e.what() << endl;
}
getchar();
}
但是,我不喜欢访问数组的界面,例如
cout << t({ 1, 1, 1 }) << endl;
看起来很丑。
是否有可能以不同的方式实现这一点,以便以更自然的方式更好地访问元素,例如cout<<t(1,1,1);
,而不是?