【问题标题】:passing a pointer to float in array to a function accepting fixed size arrays将指向浮点数的指针传递给接受固定大小数组的函数
【发布时间】:2016-11-24 12:35:32
【问题描述】:

我有许多具有以下形式的函数:

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

现在发现将大量点存储到一个长数组中很方便:

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

有没有办法将指向数组“点”的不同值的指针传递给接受固定大小数组的函数?我知道以下失败,但是,我想做类似的事情:

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

或就如何最好地重用我的代码获得任何帮助。

谢谢!

【问题讨论】:

  • 使用标准库std::vector<std::array<float,3>>

标签: c++ arrays pointers parameter-passing


【解决方案1】:

更改newDistanceToLine 的接口以使用基于模式的类型,该模式可以称为array_Viewspan - 阅读此discussion

类似这样的:

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);

所以 - 对于你的 9 元素数组,我们将有这样的用法:

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

【讨论】:

  • 可爱的答案,PiotrNycz。我会尝试这样的事情。在性能方面,您认为值得尝试 C++11 `span` 还是其他替代方案?
  • span 不应该有性能损失——它只是我介绍的通用(模板)版本。但我宁愿猜测这不是 C++11 而是一些编译器/库扩展 - 请参阅这个答案:quora.com/What-is-the-span-T-in-the-CppCoreGuidelines 但是如果你的环境中有这个 span - 那么就使用它...
  • 好吧,我刚刚编写了您的方法,将 arr3&amp; arr 更改为 arr3 (&amp;arr) 使其更灵活一点,并对其进行了模板化。效果很好!!
【解决方案2】:

改用数据结构。

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;
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-28
    • 2021-04-15
    • 2017-08-09
    • 1970-01-01
    相关资源
    最近更新 更多