2

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!

solernou
  • 235
  • 1
  • 2
  • 9

2 Answers2

3

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.

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:

newDistanceToLine(arr3_view(arr, 3), 
                  arr3_view(arr + 3, 3), 
                  arr3_view(arr + 6, 3));
Community
  • 1
  • 1
PiotrNycz
  • 23,099
  • 7
  • 66
  • 112
  • Lovely answer, PiotrNycz. I will be trying something like that. In terms of performance, do you think it is worth trying C++11 ` span `, or any other alternative? – solernou Nov 24 '16 at 13:23
  • There should be no performance penalty for span - it is just generalized (template) version of what I presented. But I rather guess this is not C++11 but some compiler/library extension - see this answer: https://www.quora.com/What-is-the-span-T-in-the-CppCoreGuidelines But if you have this `span` in your environment - then just use it... – PiotrNycz Nov 24 '16 at 15:55
  • Well, I just coded your approach, changed `arr3& arr` into `arr3 (&arr)` making it a bit more flexible, and templated it. It works beautifully!! – solernou Nov 24 '16 at 17:03
1

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;
};
arturx64
  • 943
  • 4
  • 12