简体   繁体   English

将要在数组中浮动的指针传递给接受固定大小数组的函数

[英]passing a pointer to float in array to a function accepting fixed size arrays

I have a number of functions that have the following form: 我有许多具有以下形式的函数:

typedef float arr3[3];
float newDistanceToLine(arr3 &p0, arr3 &p1, arr3 &p2);

and now find convenient to store lots of points into a long array: 现在发现将很多点存储到长数组中很方便:

int n_points = 14;
float *points;
points = new float[3*n_points];

Is there a way to pass pointers to different values of the array "points" to my functions accepting fixed size arrays? 有没有办法将指向数组“点”的不同值的指针传递给接受固定大小数组的函数? I know that the following fails, but, I would like to do something like: 我知道以下操作失败,但是,我想执行以下操作:

newDistanceToLine(&points[3], &points[6], &points[9]);

or get any help on how best to reuse my code. 或获得有关如何最好地重用我的代码的任何帮助。

Thanks! 谢谢!

Change interface of your newDistanceToLine to use type that is based on pattern that can be called either array_View or span - read this discussion . newDistanceToLine接口更改为使用基于可称为array_Viewspan模式的类型-请阅读此讨论

Something like this: 像这样:

typedef float arr3[3];
class arr3_view
{
public:
    arr3_view(arr3& arr) : data(arr) {}
    arr3_view(float* data, std::size_t size) : data(data) 
    {
        if (size != 3) // or < 3 - I am not sure what is better for your case
          throw std::runtime_error("arr3 - wrong size of data: " + std::to_string(size));
    }

    float* begin() { return data; }
    float* end() { return data + 3; }
    float& operator [](std::size_t i) { return data[i]; }
    // and similar stuff as above for const versions

private:
    float* data;
};

float newDistanceToLine(arr3_view p0, arr3_view p1, arr3_view p2);

So - for you 9-elements arrays we will have such usage: 所以-对于9个元素的数组,我们将有以下用法:

newDistanceToLine(arr3_view(arr, 3), 
                  arr3_view(arr + 3, 3), 
                  arr3_view(arr + 6, 3));

Use data structure instead. 请改用数据结构。

struct SPosition
{
SPosition( float x = 0, float y = 0, float z = 0)
    :X(x)
    ,Y(y)
    ,Z(z)
{

}
float X;
float Y;
float Z;
};

std::vector<SPosition> m_positions;

float newDistanceToLine( const SPosition& pt1, const SPosition& pt2, const SPosition& pt3 )
{
    // to do
    return 0.f;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM