Binary Serialization using Cereal

Serializing Vectors of Custom Types

How can I serialize a vector of my custom Player objects using cereal?

Abstract art representing computer programming

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 computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved