2012-03-09 77 views
2

我已經實現了diamond-square algorithm,我想以文件格式存儲地圖數據。我大多是C++初學者,或者至少在文件讀寫中,所以我有問題在哪裏存儲大量數據。C++最好的文件格式來存儲大量的地圖座標

例如,如果我創建一個65 * 65的地圖,那麼它是16384個三角形,每個都有3個座標和3個法線座標。當然,我可以將它分成4 32 * 32的地圖片,但它仍然很多。當然,真正重要的是速度,在txt中寫入所有數據沒有問題,但速度非常慢,尤其是當我增加地圖大小時。

我不是真的需要一個資源,而是需要閱讀或從中學習。

+0

該文件是否需要可移植到其他平臺? – 2012-03-09 18:14:45

+0

不,現在如果它與Windows兼容,對我來說很好。我還在學習,所以這並不重要。 – matthew3r 2012-03-09 18:17:13

+0

您可能希望有一個谷歌周圍的'三角剝離​​'。 – 2012-03-09 18:20:33

回答

5

您可以嘗試將原始二進制數據寫入您的座標。檢查出ostream::writeistream::read。或者,您可以使用讀取/寫入文件的C路(與fopen,fread,fwrite,fclose),這將避免大量的鑄造。你必須以二進制模式打開你的文件才能工作。

如果你的文件需要移植到其他平臺,你必須考慮的事情像endiannessstruct padding,整數大小等

例子:

#include <cassert> 
#include <fstream> 

struct Point {float x; float y; float z;}; 

bool operator==(const Point& p1, const Point& p2) 
{ 
    return (p1.x == p2.x) && (p1.y == p2.y) && (p1.z == p2.z); 
} 

int main() 
{ 
    Point p1 = {1, 2, 3}; 
    Point p2 = {4, 5, 6}; 

    std::ofstream out("data.dat", std::ios::binary); 

    // Write Point as a binary blob of bytes 

    // Lazy, but less portable way (there could be extra padding) 
    out.write(reinterpret_cast<const char*>(&p1), sizeof(p1)); 

    // More portable way 
    out.write(reinterpret_cast<const char*>(&p2.x), sizeof(p2.x)); 
    out.write(reinterpret_cast<const char*>(&p2.y), sizeof(p2.y)); 
    out.write(reinterpret_cast<const char*>(&p2.z), sizeof(p2.z)); 

    out.close(); 


    Point p3; 
    Point p4; 
    std::ifstream in("data.dat", std::ios::binary); 

    // Read Point as a binary blob of bytes 

    // Lazy, but less portable way (there could be extra padding) 
    in.read(reinterpret_cast<char*>(&p3), sizeof(p3)); 

    // More portable way 
    in.read(reinterpret_cast<char*>(&p4.x), sizeof(p4.x)); 
    in.read(reinterpret_cast<char*>(&p4.y), sizeof(p4.y)); 
    in.read(reinterpret_cast<char*>(&p4.z), sizeof(p4.z)); 

    assert(p1 == p3); 
    assert(p2 == p4); 
} 

您可能也對Boost.Serialization庫感興趣。它支持binary archives,這可能比文本檔案快得多。它也知道如何序列化標準庫容器。

+0

優秀的答案,謝謝,我會試試這個! – matthew3r 2012-03-10 12:53:49

相關問題