2016-11-24 54 views
2

我有許多具有以下形式的功能:指針傳遞到漂浮在數組的函數接受固定大小的數組

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

或獲取有關如何最好地重用我的代碼任何幫助。

謝謝!即基於模式的newDistanceToLine使用類型的

+1

使用標準庫'的std ::矢量<性病::陣列>' – StoryTeller

回答

3

更改界面,可以被稱爲要麼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)); 
+0

可愛的答案,PiotrNycz。我會嘗試這樣的事情。就性能而言,你認爲值得使用C++ 11'span'還是其他選擇? – solernou

+0

跨度不應該有任何性能損失 - 它僅僅是我提供的廣義(模板)版本。但我猜想這不是C++ 11,而是一些編譯器/庫擴展 - 請參閱此答案:https://www.quora.com/What-is-the-span-T-in-the-CppCoreGuidelines但是,如果你在你的環境中有'span' - 然後就使用它... – PiotrNycz

+0

嗯,我只是編寫了你的​​方法,把'arr3&arr'改成'arr3(&arr)',使它更靈活一點,並對它進行模板化。它的作品非常漂亮! – solernou

1

使用的數據結構,而不是。

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