我正在尝试编写 chunks 的向量,其中包含 Tile 的向量。写一些正确的值似乎有些不对劲。虽然它应该有25000个Tile对象,但文件的大小是4个字节...
world.cpp
Tile tile;
for (int x = 0; x < 500; x++)
{
for (int y = 0; y < 500; y++)
{
tile.setCoord(sf::Vector2i(x, y));
tile.setBiome(0);
chunk.push_back(tile);
}
}
world.push_back(chunk);
ofstream file("saves/map.dat", ios::binary | ios::out);
size_t s = world.size() * (chunk.size() * sizeof(Tile));
file.write((char *) &world, sizeof(s));
file.close();
world.hpp
class World {
public:
// World getters
int getTileSize() { return tileSize; };
int getWorldSize() { return (width * tileSize) * (height * tileSize); };
void load(const sf::String& filename);
void save(const sf::String& filename);
void draw(sf::RenderWindow& window, float dt);
World(sf::Clock clock); // new
World(const sf::String& filename, sf::Clock clock); // load
~World();
private:
const int chunkSize = 64;
int tileSize = 32; //default 32
int width, height;
std::vector<Tile> chunk;
std::vector<std::vector<Tile>> world;
sf::Clock clock;
};
如果需要,这里是tile类:
class Tile {
public:
void draw(sf::RenderTarget& target, sf::RenderStates states);
Tile();
Tile(sf::Vector2i coord, int biome);
~Tile();
sf::Vector2i getCoord() { return coord; };
int getBiome() { return biome; };
void setCoord(sf::Vector2i coord) { this->coord = coord; };
void setBiome(int biome) { this->biome = biome; };
private:
sf::Vector2i coord;
int biome;
};
我已经检查过写入的变量确实填满了所有对象。所以问题出在写作过程中,但我不知道在哪里......
答案 0 :(得分:0)
file.write((char *) &world, sizeof(s));
由于几个原因,这不会奏效。
首先,sizeof(s)
通常只有4或8个字节(取决于您的编译器以及您要定位的位数)。我认为你的意思是s
。
即使您使用s
而不是sizeof(s)
来写入数据的长度,sizeof(std::vector)
通常只有12或24个字节(大小,容量和指向数据)。那里根本没有s
个字节来写。
您的数据不是扁平结构,因此您无法一次性完成所有内容。看看序列化。有许多库可以帮助解决此问题,例如boost serialization或google protobuf,但您不必使用库。您只需要提供一个结构,您可以使用该结构编写数据并保留足够的信息以便以后重新创建数据结构。