2010-07-07 96 views
1

我試圖做到以下幾點:將靜態數組推入std :: vector?

我:

std::vector<std::vector<GLdouble[2]>> ThreadPts(4); 

然後我嘗試這樣做:

GLdouble tmp[2]; 
    while(step--) 
    { 


    fx += dfx; 
    fy += dfy; 
    dfx += ddfx; 
    dfy += ddfy; 
    ddfx += dddfx; 
    ddfy += dddfy; 
    tmp[0] = fx; 
    tmp[1] = fy; 
    ThreadPts[currentvector].push_back(tmp); 
    } 

但是編譯器說:

錯誤15錯誤C2440:'初始化':無法從'const GLdouble [2]'轉換爲'double [2]'C:\ Program Files \ Microsoft Visual Studio 9.0 \ VC \ include \ vector 1211

那我該怎麼做呢? 我使用的是VS 2008,並且沒有std :: array,我沒有提升。

由於

+0

你應該考慮諮詢您的C++的書;如果你還沒有一個,你應該考慮從[The Definitive C++ Book Guide and List]中獲取一個(http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list )。 – 2010-07-07 03:00:50

回答

2

A C樣式數組不可分配,因此它不能被用作vector的值類型。

如果您使用的是Visual C++ 2008 SP1,則可以使用#include <array>並使用std::tr1::array

即使你不想使用所有的Boost,你也應該能夠簡單地將Boost Array頭複製到你的項目中並單獨使用它;它不依賴於Boost的許多其他部分,並且它所依賴的部分可以輕鬆移除。

+0

好吧,我會使用std :: tr1 ::數組謝謝 – jmasterx 2010-07-07 02:43:30

0

可以使用一個inserter

std::copy(tmp, tmp+2, std::back_inserter(ThreadPts[currentvector])); 
2

代替2名成員原始陣列,包裝在一個結構象點:

struct Point { 
    GLDouble[2] coords; 

    void setCoordinates(GLDouble x, GLDouble y) 
    { 
    coords[0] = x; 
    coords[1] = y; 
    } 

    /* consider adding constructor(s) and other methods here, 
    * if appropriate 
    */ 
}; 

std::vector<std::vector<Point>> ThreadPts(4); 

while(step--) 
{ 
    fx += dfx; 
    fy += dfy; 
    dfx += ddfx; 
    dfy += ddfy; 
    ddfx += dddfx; 
    ddfy += dddfy; 

    Point p; 
    p.setCoordinates(fx,fy); 
    ThreadPts[currentvector].push_back(p); 
} 

它需要的內存量相同一個2元素的數組,並且具有比數組更可讀的語義。

+0

OpenGL不會喜歡這個.... – jmasterx 2010-07-07 02:50:09

+0

一致認爲,這可能在某些情況下更具可讀性,但是,該數組的優點是保證其之間沒有填充元素,如果數組必須傳遞給另一個API(如OpenGL),這非常有用。 – 2010-07-07 02:50:27

+0

編輯以反映數組中的包裝。 – 2010-07-07 02:51:30

0

你也可以使用一個std ::對

std::vector<std::vector<std::pair<GLdouble[2],GLdouble[2]> > > ThreadPts(4);