C ++ HDF5将数据集的维度用作const int

时间:2017-06-27 20:20:02

标签: c++ dataset hdf5

我想使用HDF5数据集的维度来创建数组。我正在使用以下代码来查找数据集的维度。

#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
#include <typeinfo>

#include "H5cpp.h"

using namespace H5;
int main() {
    std::string sFileName;
    sFileName = "test.h5";

    const H5std_string FILE_NAME(sFileName);
    const H5std_string DATASET_NAME("timestep:5.0");
    H5File file(FILE_NAME.c_str(), H5F_ACC_RDONLY);
    DataSet dataset = file.openDataSet(DATASET_NAME.c_str());

    DataSpace dataspace = dataset.getSpace();
    int rank = dataspace.getSimpleExtentNdims();

    // Get the dimension size of each dimension in the dataspace and display them.  
    hsize_t dims_out[2];
    int ndims = dataspace.getSimpleExtentDims(dims_out, NULL);
    std::cout << "rank " << rank << ", dimensions " <<
        (unsigned long)(dims_out[0]) << " x " <<
        (unsigned long)(dims_out[1]) << std::endl;

    const int xrows = static_cast<int>(dims_out[0]); //120
    const int yrows = static_cast<int>(dims_out[1]); //100

    std::cout << xrows * yrows << std::endl; //12000

    double myArr[xrows] // this also produces an error saying xrows is not a constant value
}

但是,当我尝试使用

创建数组时
double myArr[xrows*yrows];

我得到一个错误,说xrows和yrows不是常量值。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

double array[c]仅在c为常数值时才有效:

const int c = 10;
double array[c]; //an array of 10 doubles

c动态时,您使用new

int c = 5;
c *= 2; //c=10
double *array = new double(c);

答案 1 :(得分:0)

此类数组的大小必须是在编译时确定的常量表达式(例如,请参阅this link)。在您的情况下,您可以使用dynamic memory或STL容器,例如std :: vector。