C++动态 2D 阵列

C++ dynamic 2D array

本文关键字:阵列 2D 动态 C++      更新时间:2023-10-16

我使用以下代码来创建动态 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]等上的数组大小?

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

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

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 ;-)
}

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