如何在C ++中创建多维网格结构 [英] How to create a multidimensional grid structure in C++
本文介绍了如何在C ++中创建多维网格结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我事先不知道维数,是否可以在C ++中创建多维网格结构.
例如,我想在内存中存储一些k维数据,但是我不知道k在编译时的值,它是在运行时作为用户输入获得的.在C ++中有什么方法可以做到这一点?
在此先感谢您.
Is there anyway to create a multidimensional grid structure in C++ if I don''t know the number of dimensions in advance.
For example I want to store some k dimensional data in the memory, but I don''t know the value of k at compile time, it is obtained as a user input at run time. Is there any way of doing this in C++ ?
Thanks in advance.
推荐答案
有动态内存分配,因此您可以这样做.请注意,随着k
的增加,您很快就会用完内存.
:)
There''s dynamic memory allocation, hence you can do that. Beware, ask
increases, you will quickly run out of memory.
:)
是的,您当然可以在C ++中做到这一点.
不,没有内置的东西可以帮您完成现成的事情.
正如CPallini指出的那样,它将需要使用动态内存分配.
最近有一个相关的问题.基于此,这是一个可能的起点.当心这是现成的,不要尝试编译.它不包含错误检查.它甚至可能包含明显的错误.
Yes, you can certainly do that in C++.
No, there isn''t anything built in that will do it for you ready made.
As CPallini indicated, it will require the use of dynamic memory allocation.
There was a somewhat related question recently. Based on that, here is a possible starting point. Beware this is off-the-cuff with no attempt to compile. It contains no error checking. It may even contain glaringly obvious errors.
template<typename T>
class multiDimArray
{
public:
multiDimArray( const std::vector<size_t> &dimensions ) :
dimensions_( dimensions ), pContents(NULL);
{
size_t size = 1;
std::vector<size_t>::const_iterator dimIter = dimensions_.begin();
for ( ; dimIter != dimensions_.end(), ++dimIter )
{
size *= *dimIter;
}
pContents = new T[ size ];
}
~multiDimArray( )
{
delete [] pContents;
}
T& operator()( const std::vector<size_t> &indicies )
{
std::vector<size_t>::const_iterator indexIter = indicies.begin();
std::vector<size_t>::const_iterator dimIter = dimensions_.begin();
// calculate offset into linear array
size_t offset = 0;
++dimIter; // first dimension isn''t used in the calculation
for ( ; dimIter != dimensions_.end(); ++dimIter, ++indexIter )
{
offset += *indexIter;
offset *= *dimIter;
}
offset += *indexIter; // add last index value
return *(pContents + offset);
}
std::vector<size_t>size_type NumberOfDimensions() const
{
return dimensions_.size();
}
private:
T *pContents;
std::vector<size_t> dimensions_;
};
类似的声音基本线性代数库 [
Sounds like Basic Linear Algebra Library[^] fits the bill, supports sparse matrices.
Regards
Espen Harlinn
这篇关于如何在C ++中创建多维网格结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文