Reading and writing a std::vector into a file correctly

后端 未结 5 1218
梦毁少年i
梦毁少年i 2020-12-01 04:26

That is the point. How to write and read binary files with std::vector inside them?

I was thinking something like:

//============ WRITING A VECTOR IN         


        
5条回答
  •  既然无缘
    2020-12-01 05:23

    Before reading vector, you should resize it: yourVector.size(numberOfElementsYouRead).

    Besides, sizeof(vector) is just the size of the vector object internal implementation; vector element size is sizeof(std::vector::value_type).

    Then read it like this:

    file.read(reinterpret_cast(&myVector[0]), sizeof(vector::element_type) * element_count); 
    

提交回复
热议问题