HDF5存储不同大小的字符串属性

HDF5 Store string attributes with different sizes

本文关键字:字符串 属性 存储 HDF5      更新时间:2023-10-16
  • 语言:c++
  • 软件包:HDF5,版本1.6.8

我目前正在使用以下代码来存储一个真实的数组作为属性:

oid storeStringAttribute(H5::H5Location& group, string name, vector<double>& array)
{
    hsize_t dims[1];
    dims[0] = array.size();
    H5::DataSpace dataspace = H5::DataSpace(1, dims);
    H5::Attribute attribute = group.createAttribute(name.c_str(), NATIVE_DOUBLE, dataspace);
    attribute.write(H5::PredType::NATIVE_DOUBLE, vec.data());
}

我想写一个类似的代码来存储vector<string>数组有没有一种简单的方法来存储可变大小的字符串数组

我目前正在做的是使用更大的尺寸,但这不是很有效。

void storeStringAttribute(H5::H5Location& group, string name, vector<string>& array)
{
    hsize_t dims[1];
    dims[0] = array.size();
    size_t maxStringSize = 0;
    for(size_t i=0; i<array.size(); i++)
    { maxStringSize = std::max(maxStringSize, array.size()); }
    H5::StrType strdatatype(H5::PredType::C_S1, maxStringSize+1);
    H5::DataSpace dataspace = H5::DataSpace(1, dims);
    H5::Attribute attribute = group.createAttribute(name.c_str(), strdatatype, dataspace);
    attribute.write(strdatatype, vec.data());
}

答案如下:

void storeStringAttribute(H5::H5Location& group, string name, vector<string>& array)
{
    hsize_t dims[1];
    dims[0] = array.size();
    H5::StrType strdatatype(H5::PredType::C_S1, maxStringSize+1);
    strdatatype.setSize(H5T_VARIABLE);
    H5::DataSpace dataspace = H5::DataSpace(1, dims);
    H5::Attribute attribute = group.createAttribute(name.c_str(), strdatatype, dataspace);
    attribute.write(strdatatype, vec.data());
}