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