C ++动态2D数组

时间:2012-12-10 14:02:54

标签: c++

我使用以下代码创建动态2D数组。

uint32_t** arrays = new uint32_t*[10]; 
uint32_t number = take input from console ;
arrays[0] = new uint32_t[number];
number = take input from console ;
arrays[1] = new uint32_t[number];
delete arrays[0] ;
number = take input from console ;
arrays[0] = new uint32_t[number] ;

任何人都可以帮助我在不知道输入值的情况下如何知道第二维的大小?意味着如何在数组[0],数组[1]等上找到数组大小?

3 个答案:

答案 0 :(得分:3)

在不存储大小值的情况下,无法确定new分配的内存块的大小。

编辑:另外,为什么不使用vector< vector< uint32_t > > arrays;

答案 1 :(得分:1)

std::vector<std::valarray<uint32_t> >也可能是另一种选择。 假设您的控制台程序将进行某种计算,那么相当未知的std::valarray将是一个很好的伴侣。

请注意用户提供的大小值可能导致std::bad_alloc异常的风险,因此您可以将分配至少放入try / catch块。

另一个解决方案是在容器中收集所有用户提供的大小值,然后为数据实例化另一个单个容器:

//Disclaimer: below code has never been tested and is rather about how to do such stuff in general,
//regardless of the few bytes gained for sacrificing CPU cycles.

#include <vector>
#include <valarray>
#include <numeric>
#include <cassert>
#include <exception>

void app(void)
{
    std::vector<size_t> sizes;
    std::valarray<uint32_t> data;

    try
    {
        //collect N user defined sub-vector size values in 'sizes'
        //.
        //.
        //.
        size_t totalNumberOfValues = std::accumulate(sizes.begin(),sizes.end(),0u);
        data.resize(totalNumberOfValues);
    }
    catch(std::bad_alloc& e)
    {
        //handle error
    }

    //accessing the minor/sub-vectors using the size values requires accumulation of adjacent size values of preceding sub-vectors.    
    //of course, these offsets could also be pre-computed.

    size_t subVectorIndex /*...*/; //needs to be checked!
    assert(subVectorIndex < sizes.size());

    size_t subVectorSize = sizes[subVectorIndex];
    size_t subVectorOffset = std::accumulate(sizes.begin(),sizes.begin()+subVectorIndex,0u);

    //do NOT reallocate 'data' while twiddling around with pointers!
    uint32_t* subVectorData = &data[subVectorOffset];

    //well, using neat stuff like std::slice, std::gslice etc. is up to you now ;-)
}

答案 2 :(得分:0)

没有办法做到这一点。为了提高存储器效率,分配的存储器块的大小不能保证存储在任何地方。考虑使用向量而不是第二维的普通数组。