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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?