c++ - HDF5:在数据集中插入一组字符串

标签 c++ string api hdf5

我目前正在学习 HDF5 API,我正在尝试将一组 C++ std::string 插入到 HDF5 数据集(1 列)中。

在下面的片段中,我应该如何遍历 vector<string>并在正确的索引处插入每个字符串?

我应该如何告诉 HDF5 我想使用固定长度的字符串还是可以有任意长度的 std::string ?

vector<string> samples;
(...)
/* create HDF5 file */
hid_t       hdf5file= H5Fcreate(hdf5_filename, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
if(hdf5file==-1)
    {
    cerr << "Cannot create HDF5 file "<< hdf5_filename << endl;
    return(EXIT_FAILURE);
    }
/* create a group in this file */
hid_t    group = H5Gcreate2(hdf5file, "/MyGroup", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
if(group==-1)
    {
    cerr << "Cannot create HDF5 group  "<< endl;
    return(EXIT_FAILURE);
    }
/* create a dataspace for the samples array of one dimension */
hsize_t dim1=samples.size();
hid_t dataspace = H5Screate_simple(1, &dim1, NULL);
if(dataspace==-1)
    {
    cerr << "Cannot create HDF5 dataspace  "<< endl;
    return(EXIT_FAILURE);
    }
/* create datatype for a string . How shoud I tell if i want a fixed-length string or a can-have-any-length string ?*/
hid_t datatype = H5Tcopy(H5T_C_S1);
if(datatype==-1)
    {
    cerr << "Cannot create H5Tset_size  "<< endl;
    return(EXIT_FAILURE);
    }
int ret = H5Tset_size (datatype, H5T_VARIABLE);
if(ret!=0)
    {
    cerr << "Cannot create H5Tset_size  "<< endl;
    return(EXIT_FAILURE);
    }
hid_t dataset = H5Dcreate2(group, "Samples", datatype, dataspace,
        H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);

for(vector<string>::size_type i=0;i< samples.size();++i)
    {
    /** here I'm puzzled, how should I insert the value of samples[i].c_str() at
            the i-th index of the dataset ? */
    const char* sampleName= samples[i].c_str() ;
    ????
        ????
    ????
    }

/* close data set */
H5Dclose(dataset);
/* close datatype */
H5Tclose(datatype);
/* close the dataspace */
H5Sclose(dataspace);


/* close the group */
 H5Gclose(group);

/* close hdf5 file */
H5Fclose(hdf5file);

最佳答案

首先,创建一个 C 风格的 char* 数组,其中包含指向您的字符串的指针:

const size_t n = samples.size();
char* data[n];
for (size_t i = 0; i < n; i++)
{
    data[i] = samples[i].c_str();
}

然后一口气写完:

H5Dwrite(dataset, datatype, dataspace, H5S_ALL, H5P_DEFAULT, data);

关于c++ - HDF5:在数据集中插入一组字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6184817/

相关文章:

c# - String NULL 是否总是等于 C# 中的另一个 String NULL?

通过 API 确认 paypal 商品已售出

c# - 在 C# 上编写 Messenger Telegram 的难点

c++ - 一次包含已在 main.obj 中定义的 .h 函数

string - 等于后缀的前缀数

python - 在python 3中查找字符串中某个单词的出现

python - fastapi.Response() 不返回自定义响应

c++ - stdafx 是否需要在同一目录中?

C++线程程序不会终止

C++ - 位图的 10 种最流行的颜色