To serialize a vector of custom Player
objects using cereal:
Step One: Make sure your Player
 class has the necessary serialize
 (or save
/load
) functions defined, as shown in the lesson.
Step Two: Include the required cereal headers:
#include <cereal/archives/binary.hpp>
#include <cereal/types/vector.hpp>
Step Three: Create your vector of Player
 objects:
std::vector<Player> players;
players.emplace_back("Alice", 10);
players.emplace_back("Bob", 20);
Step Four: Serialize the vector using a cereal output archive:
std::ofstream file("players.dat");
cereal::BinaryOutputArchive archive(file);
archive(players);
Step Five: To deserialize the vector, use a cereal input archive:
std::ifstream file("players.dat");
cereal::BinaryInputArchive archive(file);
std::vector<Player> loadedPlayers;
archive(loadedPlayers);
After this, loadedPlayers
will contain the deserialized Player
objects from the file. Here is a complete example:
#include <cereal/archives/binary.hpp>
#include <cereal/types/string.hpp>
#include <cereal/types/vector.hpp>
#include <fstream>
#include <iostream>
#include <vector>
class Player {
public:
Player() = default;
Player(const std::string& name, int level)
: name(name), level(level) {}
std::string name;
int level;
private:
friend class cereal::access;
template <class Archive>
void serialize(Archive& ar) {
ar(name, level);
}
};
int main() {
std::vector<Player> players;
players.emplace_back("Alice", 10);
players.emplace_back("Bob", 20);
{
std::ofstream file("players.dat",
std::ios::binary);
cereal::BinaryOutputArchive archive(file);
archive(players);
}
std::vector<Player> loadedPlayers;
{
std::ifstream file("players.dat",
std::ios::binary);
cereal::BinaryInputArchive archive(file);
archive(loadedPlayers);
}
for (const auto& player : loadedPlayers) {
std::cout << player.name << " (Level "
<< player.level << ")\n";
}
}
Alice (Level 10)
Bob (Level 20)
Answers to questions are automatically generated and may not have been reviewed.
A detailed and practical tutorial for binary serialization in modern C++ using the cereal
library.