我已经实现了diamond-square algorithm我想以文件格式存储 map 数据。我主要是 C++ 的初学者,或者至少是文件读写的初学者,所以我在哪里存储大量数据存在问题。
例如,如果我创建一个 65*65 的 map ,那么它有 16384 个三角形,每个三角形有 3 个坐标,3 个法线坐标。当然我可以把它分成例如4个32*32的 map block ,但还是很多。当然真正重要的是速度,将所有数据写入txt中没有问题,但是确实很慢,尤其是当我增加 map 大小时。
我并不是真的需要一个来源,而是需要一些可以阅读或从中学习的东西。
最佳答案
您可以尝试将坐标写入原始二进制数据。查看ostream::write
和istream::read
。或者,您可以使用 C 方式读取/写入文件(使用 fopen
、fread
、fwrite
、fclose
),这将避免大量的类型转换。您必须以二进制模式打开文件才能使其工作。
如果您的文件需要移植到其他平台,则必须考虑类似 endianness 的内容。 , struct 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 ,这可能比文本文件快得多。它还知道如何序列化标准库容器。
关于C++ 存储大量 map 坐标的最佳文件格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9638874/