c++ – How do I write a 2D vector to a binary file?


Suppose I have some kind of 2D vector:

std::vector<std::vector<int>> main_vector;
std::vector<int> temp_vector;

for (std::size_t i = 0; i < 5; i++) temp_vector.push_back(i);
for (std::size_t i = 0; i < 5; i++) main_vector.push_back(temp_vector);

How do I write it to a binary file? Accordingly, the dimension is unknown. I know that it won't work in a standard way as with arrays.

bin_file.open("test.txt", std::ios::out | std::ios::binary);
bin_file.write((char *)&main_vector, sizeof(main_vector)); //не сработает


For greater generalization, we will assume that vectors inside a vector can have different sizes.

Then approximately (I don't compile – just a sketch!)

// Пишем размер внешнего вектора
size_t sz = main_vector.size();

for(size_t i = 0; i < sz; ++i)
    // То же самое для каждого внутреннего:
    vector<int>& v = main_vector[i];
    size_t sz = v.size();
    // Пишем данные
    for(size_t j = 0; j < sz; ++j)
        int n = v[j];
    // Или, поскольку в векторе данные лежат подряд -
    // просто stream.write(v.data(), sizeof(int)*sz);

Read – in reverse order. First – the total number of vectors inside the main one, then a loop through them – reading the number of int'ov and reading and inserting the corresponding number of values ​​(or, again, creating a vector with a known number of elements and reading directly into the internal buffer …)

Scroll to Top