我需要根据用户的输入存储一些数据。我的程序应该根据从cin获得的int值创建不同的数据结构。
例如,值0存储标量、1向量、2-2 3dArray、3-3 3dArray、4- 4d数组等.
我的问题是,是否有可能编写一些代码来做到这一点。
我知道这听起来可能很混乱,所以我将提供一些更多的例子。
假设用户输入0 5,那么我的程序应该创建一个int变量并将5存储在其中。
如果用户输入1 5,7,6,我的程序应该创建一个向量= {5,7,6};
如果用户输入2,2,3,1,2,3,4,5,6,我的程序应该创建一个2d数组a2并将值存储在那里。
如果我知道用户将拥有的最大维数,我可以找到一个解决方案,但是分配的目标是可以指定任意数量的维度.
请帮帮忙
发布于 2016-09-27 00:01:41
如果您放松一些需求(“基于我从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::载体的变异体
类似于:
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)];
}
}发布于 2016-09-26 23:32:23
int)if() {} else if() {}等)。struct Scalar{}、struct Vector{}等。read()方法来读取用户输入的其余部分。(您需要使用某种机制来拆分用户输入,提示:字符串标记)发布于 2016-09-27 00:20:51
您可以对所有类型的用户输入使用普通std::vector。唯一需要的是一些函数f(x),它将索引的k大小向量映射到平面数组中的索引。
例如:x-k大小的索引向量,s-k大小的尺寸向量。
k = 1 -> f1(x,s) = x1;
k = 2 -> f2(x,s) = x2*s2 + x1;
k = 3 -> f3(x,s) = x3*s3*s2 + x2*s2 + x1 = x3*s3*s2 + f2(x2,x1,s2,s1);
k = 4 -> f4(x,s) = x4*s4*s3*s2 + f3(x3,x2,x1,s3,s2,s1);最后坐标的乘子是(k - 1)维对象的体积.另外,我们认为坐标的计算是从0开始的。
这看起来像递归函数,可以很容易地实现。您只需计算(k - 1)维对象的移位,从数组中计算pop坐标,并再次从自身调用函数。
https://stackoverflow.com/questions/39713818
复制相似问题