0

免责声明:这东西不是我的专长。

我正在尝试使用 NumCPP 包将 2 个不同的 3 列 1 行数组输入到 linspace 函数中,但我遇到了以下错误:

“没有函数模板的实例“nc::linspace”与参数列表匹配——参数类型为:(float,float,int)”<--来自 VSCode intelisense 和“错误:无法将 'float' 转换为 'float** '" 在终端中运行时。

与此错误相关的代码如下:

float** XYZ[3]; 
float** function(float array_A, float array_B, int C) { 
XYZ** = nc::linspace<float**>(array_A, array_B, C); 
return XYZ;
};

在 main 函数中的代码结束时,我将这些参数定义为:

 float array_A [3]= {0,0,0};
 float array_B [3]= {0,PI/4,0};
 int C = 10000;

我使用 numpy 的 linspace 函数对 python 做了同样的事情,没有问题。C++ 很难,所以任何帮助表示赞赏。

4

1 回答 1

0

这是一个如何做的例子(没有“C”风格的数组)

#include <cassert>
#include <iostream>
#include <vector>
#include <NumCpp/Functions/linspace.hpp>

// in C++ std::vector (or std::array) are preferred over manually allocated "C" style arrays.
// this will avoid a lot of issues related to (pointer) type decay in which actual size information 
// of arrays is lost, and it will avoid manual memory managment with new/delete.

// pass vector's by const& so they won't be copied
// make number_of_samples a size_t type since it should never be < 0 (which is allowed by int)
auto linspace(const std::vector<double>& arr1, const std::vector<double>& arr2, const std::size_t number_of_samples)
{
    std::vector<std::vector<double>> retval;
    assert(arr1.size() == arr2.size());

    for (std::size_t n = 0; n < arr1.size(); ++n)
    {
        // linspace documentationhttps://dpilger26.github.io/NumCpp/doxygen/html/namespacenc.html#a672fbcbd2271d5fc58bd1b94750bbdcc
        // in C++ linspace only accepts values, not array like stuff.
        nc::NdArray<double> sub_result = nc::linspace(arr1[n], arr2[n], static_cast<nc::uint32>(number_of_samples));

        // construct a std::vector<double> from nc::NdArray and put it at back of return value
        retval.emplace_back(sub_result.begin(), sub_result.end());
    }

    return retval;
}

int main()
{
    // Create two dynamically allocated arrays of doubles
    std::vector<double> array_A{ 0.0, 1.0, 2.0 };
    std::vector<double> array_B{ 4.0, 5.0, 6.0 };

    // do a linspace on them (linespace is what you called function)
    const std::size_t number_of_samples = 4;
    auto result = linspace(array_A, array_B, number_of_samples);

    // and show the output
    std::cout << "result of linspace : \n";

    for (const auto& arr : result)
    {
        bool comma = false;
        // range based for loop over the result array to display output
        for (const auto& value : arr)
        {
            if (comma) std::cout << ", ";
            std::cout << value;
            comma = true;
        }
        std::cout << "\n";
    }

    return 0;
}
于 2021-11-28T05:45:27.517 回答