如果您放宽一些要求(“根据我从 cin 获得的 int 值创建不同的数据结构”),这是可能的。这只是一个草图,不是完整的答案,但希望它能让你走上正轨。
访问存储空间:
您需要将数字存储在所需类型的单个数组中,并通过索引映射函数包装对它们的访问。
例如,在 2D 中,一个这样的函数是
int indexIn2D(uint rowCol[2], int rowCount) {
// rowCol[0] - is row index, rowCol[1] is col index
return rowCol[0]*rowCount + rowCol[1];
}
float* values=new float[numRows*numCols];
// I want the element at (i,j)
float& myIJElement=values[indexIn2D({i,j}, numRows)];
将其转换为 N 维将需要以下内容
// suppose I'm storing a 3D matrix with [3 slices, 4 rows, 5 columns]
// as a 1D array and I want the element at [x,y,z] - what's it would be
// the position of that element in my 1D array?
// - fill coodIndex[3] with {x,y,z}
// - pass nDim=3
// - the dimSignature will be {3 /*slices*/, 4 /*rows*/, 5 /*columns*}
int indexInND(uint coordIndex[], uint numDim, uint[] dimSignature) {
int ret=coordIndex[0];
for(uint i=0; i<numDim-; i++) {
ret=ret*dimSignature[i]+coordIndex[i+1];
}
return ret;
}
类似变体的存储类型
好吧,我们已经知道我们会将整个“N-dim 块”存储为目标类型的unidim 数组。所以我们可以利用指针,让我们的“存储”类似于
struct NDimStorage {
// 0 for int, 1 for float, etc.
int whichType; // or make it enum
union {
int* int_st;
float* float_st;
};
uint numDims;
uint dimSignature[];
};
std::vector 的后备 fom 变体
类似:
template <typename NumType> class VectNStorage {
std::vector<NumType> storage;
std::vector<uint> dimSignature;
protected:
size_t indexMapping(const std::vector<uint>& indices) {
size_t ret=indices[0];
for(uint i=0; i<this->dimSignature.size()-1) {
ret=ret*this->dimSignature[i]+indices[i+1];
}
return ret;
}
public:
VectNStorage(const std::vector<uint> dimsDef) : storage(), dimSignature(dimsDef) {
uint howMany=1;
for(auto d : this->dimSignature) {
howMany*=d;
}
this->storage.resize(howMany);
std::fill(this->storage.begin(), this->storage.end(), 0);
}
NumType& at(const std::vector<uint>& indices) {
return this->storage[this->indexMapping(indices)];
}
}