How do I serialize and deserialize contents with std::vector in performance-sensitive code?

In performance-sensitive C++ applications, serializing and deserializing data structures like `std::vector` can be done efficiently using various methods. Here’s an example using binary serialization for optimal performance.

Serialization, Deserialization, std::vector, C++, Performance Optimization, Binary Serialization

This content provides an example of serializing and deserializing a `std::vector` in C++, highlighting performance-sensitive techniques. Ideal for developers looking to improve data handling in their applications.

#include <iostream> #include <vector> #include <fstream> template <typename T> void serialize(const std::vector<T>& vec, const std::string& filename) { std::ofstream ofs(filename, std::ios::binary); size_t size = vec.size(); ofs.write(reinterpret_cast<const char*>(&size), sizeof(size)); ofs.write(reinterpret_cast<const char*>(&vec[0]), size * sizeof(T)); } template <typename T> void deserialize(std::vector<T>& vec, const std::string& filename) { std::ifstream ifs(filename, std::ios::binary); size_t size; ifs.read(reinterpret_cast<char*>(&size), sizeof(size)); vec.resize(size); ifs.read(reinterpret_cast<char*>(&vec[0]), size * sizeof(T)); } int main() { std::vector<int> nums = {1, 2, 3, 4, 5}; serialize(nums, "data.bin"); std::vector<int> new_nums; deserialize(new_nums, "data.bin"); for (int num : new_nums) { std::cout << num << " "; } return 0; }

Serialization Deserialization std::vector C++ Performance Optimization Binary Serialization