c++ - xtensor:将 View 分配给 double

标签 c++ xtensor

我正在尝试通过xtensor库实现滚动平均alapandas。但是,我无法将表达式 xt::mean(x_window) 分配给 double result[i]

#include <iostream>
#include <xtensor/xarray.hpp>
#include <xtensor/xio.hpp>
#include <xtensor/xview.hpp>
#include <xtensor/xadapt.hpp>
#include <vector>

// implement rolling mean
template<typename T>
xt::xarray<T> rolling_mean(const xt::xarray<T> &x, const int window) {
    const auto nan = std::numeric_limits<T>::quiet_NaN();
    xt::xarray<T> result = xt::full_like(x, nan);
    for (int i = 0; i < x.shape()[0] - window + 1; i++) {
        auto x_window = xt::view(x, xt::range(i, i + window));
        result[i + window - 1] = xt::mean(x_window); // <-- problematic step
    }
    return result;
}

int main(int argc, char *argv[]) {
    using T = double;
    std::vector<T> v = {1, 2, 3, 4, 5};
    xt::xarray<T> a = xt::adapt(v);
    std::cout << rolling_mean(a,2) << std::endl; // [nan, 1.5, 2.5, 3.5, 4.5] expected
}

如何解决这个问题?

编译失败并出现错误消息

error: assigning to 'double' from incompatible type 'xt::xfunction<xt::detail::divides, xt::xreducer<xt::xreducer_functors<xt::detail::plus, xt::const_value<double>>, const xt::xview<xt::xarray_container<xt::uvector<double, xsimd::aligned_allocator<double, 16>>, xt::layout_type::row_major, xt::svector<unsigned long, 4, std::allocator<unsigned long>, true>> &, xt::xrange<long>> &, xt::svector<unsigned long, 4, std::allocator<unsigned long>, true>, xt::reducer_options<double, std::tuple<xt::evaluation_strategy::lazy_type>>>, xt::xscalar<double>>'

最佳答案

问题是您实际上并没有调用 xt::mean 产生的可调用函数,而是尝试分配 xt::mean 的结果double

解决这个问题,只需添加括号()来调用它,然后将其分配给double,如下所示:

//----------------------------vv---->added this parenthesis
result[i] = xt::mean(x_window)();

关于c++ - xtensor:将 View 分配给 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72569161/

相关文章:

Numpy vs Eigen vs Xtensor 线性代数基准奇数

c++ - 访问冲突写入位置 0xcccccccc 使用字符串

c++ - 在 xarray 中按索引分配值会分配整个数组

c++ - 程序编译失败

c++ - seekg、tellg、从零开始的计数和文件大小

indexing - Xtensor 返回值为 NaN 的索引

c++ - 在 xtensor 中使用 xt::where 时遇到问题

c++ - xtensor:选择具有特定列值的行

C++ Eigen 库 : Performance overhead of Ref<>

c++ - 无法让 boost::thread 与 MSVS2013 一起工作