繁体   English   中英

使用fstream编写类型的向量

[英]using fstream to write vector of types

我正在尝试编写包含Tile s向量的块的向量。 写一些正确的值似乎有些不对劲。 虽然它应该有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;
};

我已经检查过写入的变量确实填满了所有对象。 所以问题出在写作过程中,但我不知道在哪里......

file.write((char *) &world, sizeof(s));

由于几个原因,这不起作用。

首先, sizeof(s)通常只有4或8个字节(取决于你的编译器和你所针对的位数)。 我认为你的意思就是s

即使您使用s而不是sizeof(s)来写入数据的长度, sizeof(std::vector)通常只有12或24个字节(大小,容量和指向数据的指针)。 那里根本就没有s字节可写。

您的数据不是扁平结构,因此您无法一次性完成所有数据。 看看序列化。 有许多库可以帮助解决这个问题,例如boost序列化谷歌protobuf ,但你不一定要使用库。 您只需要提供一个结构,您可以使用该结构编写数据并保留足够的信息以便以后重新创建数据结构。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM