【问题标题】:C++ HDF5 Use dimensions of dataset as const intC++ HDF5 使用数据集的维度作为 const int
【发布时间】:2017-12-01 00:46:05
【问题描述】:

我想使用我的 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 不是常量值。我该如何解决这个问题?

【问题讨论】:

    标签: c++ dataset hdf5


    【解决方案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);
    

    【讨论】:

    • xrows 和 yrows 是常数值,所以 xrows*yrows 不应该也是常数吗?
    • 没有。当任何微积分完成时,'const' 会丢失。 const 是编译器问题。微积分在运行时完成。
    • 哦,即使我尝试加倍 myArr[xrows],它也不起作用。它认为 xrows 不是一个常数,即使我将它定义为一个
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2013-03-25
      • 2018-03-25
      • 2010-09-14
      • 2017-09-06
      • 2018-10-28
      • 2019-06-09
      • 1970-01-01
      • 2022-11-14
      • 1970-01-01
      相关资源
      最近更新 更多