【发布时间】:2021-12-16 03:28:49
【问题描述】:
我想将向量中包含的值传递给一个新变量。但是好像类型转换有问题,因为反复抛出错误:
error: cannot convert 'float*' to 'double' in
initialization
error: cannot convert 'std::vector<float>' to
'double' in initialization
我尝试更改向量和变量的数据类型,但错误不断出现!
#include <boost/multi_array.hpp>
#include <h5xx/h5xx.hpp>
#include <iostream>
#include <vector>
#include <algorithm>
using array_2d_t = boost::multi_array<float, 2>;
h5xx::dataset open_dataset(std::string const& filename) {
h5xx::file xaa(filename, h5xx::file::mode::in);
h5xx::group g(xaa, "particles/lipids/box/positions");
return h5xx::dataset(g, "value");
}
std::vector<float> cell_from_all_frames(h5xx::dataset& ds, size_t row, size_t col) {
// determine dataset shape: frames, particle count, space dimension
auto ds_shape = h5xx::dataspace(ds).extents<3>();
std::vector<float> cells(ds_shape[0]); // number of frames
std::vector<hsize_t> offsets{0, row, col};
std::vector<hsize_t> counts{ds_shape[0], 1, 1};
h5xx::slice slice(offsets, counts);
h5xx::read_dataset(ds, cells, slice);
return cells;
}
int main(int argc, char const* argv[])
{
if (argc < 2) {
std::cout << "Usage: " << argv[0] << " input.h5" << std::endl;
return -1;
}
auto ds = open_dataset(argv[1]);
std::vector<float> first_cells = cell_from_all_frames(ds, 0, 0);
size_t nsamples = first_cells.size();
std::cout << "no. of samples: " << nsamples ;
double sampling_interval = 1; // time between samples
correlator::multi_tau_correlator<double> corr( // TODO replace sample type
nsamples * sampling_interval / 30 // max lag time: fraction of total trajectory length
, sampling_interval // time resolution at lowest level
, 10 // block size // FIXME pass as (optional) command line argument
);
// define time correlation functions
auto msd = make_correlation(correlator::mean_square_displacement(), corr);
corr.add_correlation(msd);
// main loop
for (size_t i = 1; i < nsamples; ++i) {
double position_array = first_cells();
//double position_array = static_cast<double>(std::rand()) / RAND_MAX;
std::cout << "position arrays: " << position_array << std::endl;
// append data to the correlator, which possibly computes some time correlations
corr.sample(position_array);
}
corr.finalise();
return 0;
}
问题在于注释主循环下的 main() 函数。我想将存储在 first_cells 中的值传递给 position_array,但它会引发上述错误。我尝试传递一些随机数并猜猜是什么,它工作正常!
【问题讨论】:
-
double position_array不是一个数组,它只是一个数字。不知道你想要什么,请添加corr::sample的声明并请删除95%与问题无关的代码。 -
@Quimby 不,它只是一个变量名,将传递给 corr.sample(position_array)。你是说 position_array 应该先初始化一个数组吗?
-
不不,这不是 Python,变量具有类型,并且这些类型在其生命周期内无法更改。所以如果
first_cells返回某个类型,position_array必须有兼容的类型,或者使用auto。我不知道在暗示什么,因为我不知道你想要什么样的数组。基于first_cells我猜std::vector<float> position_array但我不知道cor::sample接受什么类型。 -
如果您只想将其传递给其他地方,那么
auto position_array = first_cells();会为您推断出正确的类型。 -
cor::sample 接受双精度类型。我通过传递双随机数进行了检查。