1

我正在使用以下代码创建动态二维数组。

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]等上找到数组大小?

4

3 回答 3

3

new如果不存储大小值,就无法确定分配的内存块的大小。

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

于 2012-12-10T14:04:44.073 回答
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 ;-)
}
于 2012-12-10T15:41:42.887 回答
0

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

于 2012-12-10T14:06:08.083 回答