You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++三维数组适配boost接口编译报错,需指定何种正确数据类型?

问题根因与修复方案

错误原因

  • sample_type类型定义错误
    你当前代码中typedef boost::multi_array_types::size_type sample_type;里的size_type是boost提供的无符号长整型标量,仅用于表示数组长度,本身不是数组类型。你把算子operator()的三个入参都定义为该标量类型,就是两个编译报错的直接原因:

    报错1:尝试对标量msd_x调用不属于它的.size()成员方法
    报错2:尝试对单个整数用[][]执行数组下标访问

  • 相关器模板参数不匹配
    main函数中你定义correlator::multi_tau_correlator<double> corr时填的模板参数是double,但你实际传入corr.sample()的position_array是多维数组类型,类型不匹配导致相关器传给算子的入参被自动转换为标量,进一步放大了类型错误。
  • 隐性语法问题
    算子内dr变量定义在j循环内部,外层循环访问dr * dr时会触发作用域报错;mean_square_displacement类定义末尾缺少分号,也会触发编译错误。

修复方案

  1. 修正sample_type定义,替换为你实际使用的多维数组类型,以2维double类型boost数组为例:
class mean_square_displacement
{
public:
    // 替换为实际的多维数组类型,维度根据position_array的实际维度调整
    typedef boost::multi_array<double, 2> sample_type;
    typedef double result_type;

    result_type operator() (sample_type const& msd_x, sample_type const& msd_y, sample_type const& msd_z) const
    {
        size_t N = msd_x.size();
        result_type msd = 0;
        for (unsigned int i = 0; i < N; ++i) {
            result_type dr = 0; // 把dr移到j循环外
            for (unsigned int j = 0; j < N; ++j) {
                dr += (msd_x[i+1][j] - msd_x[i][j])  + (msd_y[i+1][j+1] - msd_y[i][j+1]) + (msd_z[i+1][j+2] - msd_z[i][j+2]); 
            }
            msd += dr * dr;
        }
        return msd / N;
    }
}; // 补全类定义末尾的分号
  1. 修正相关器的模板参数,和sample_type保持一致:
int main(int argc, char const* argv[])
{
    // 把模板参数从double替换为对应的数组类型
    correlator::multi_tau_correlator<mean_square_displacement::sample_type> corr(
        nsamples * sampling_interval / 30,
        sampling_interval,
        10   
    );
    auto msd = make_correlation(correlator::mean_square_displacement(), corr);
    corr.add_correlation(msd);
    for (size_t i = 1; i < nsamples; ++i) {
        auto position_array = first_rows[i]; 
        corr.sample(position_array);
    }
    corr.finalise();
    return 0;
}

内容的提问来源于stack exchange,提问作者Mahesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 05:15:07