C++动态 2D 阵列
C++ dynamic 2D array
我使用以下代码来创建动态 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 ;-)
}
没有办法做到这一点。为了提高内存效率,不保证分配的内存块的大小存储在任何地方。考虑对第二维使用向量而不是普通数组。
相关文章:
- C++动态安全 2D 交错阵列
- 库特<<恩德尔;不适用于打印 2D 阵列
- 具有可变尺寸的 C++ 2D 阵列
- 如何通过Boost.MPI发送2d Boost.MultiArray的子阵列?
- 如何从2d Boost.MultiArray获取子阵列?
- 基于用户输入的 2D 动态阵列
- 2D 动态阵列被视为特洛伊木马?
- 如何遍历 2D 阵列?
- 超级对撞机2D阵列:生成嵌套:包装/尺寸问题
- 动态 2D 阵列.为什么分段错误?
- 尝试使用2D阵列
- 分配给阵列时出现分段错误?黑客排名 2D 阵列 - DS.
- 如何将1D阵列访问为2D阵列
- 分配/访问2d阵列,使得2d子块是连续的
- 重新分配2D阵列并删除旧阵列
- 不使用新的动态2D阵列
- 我正在为2D阵列参数而挣扎
- 特征和巨大的密集 2D 阵列
- 全球字符阵列(2D)
- 如何将内存映像分配给DLIB阵列2d或映像