简体   繁体   中英

Writing and reading vector to a binary file

std::vector<cv::Point3f> data;
//loop invoking 
//cv::Point3f p; p.x=..; p.y=..; p.z=.. and data.push_back(p)

std::ofstream myFile("data.bin", ios::out || ios::binary);
myFile.write(reinterpret_cast<char*> (&data[0]), sizeof(cv::Point3f)*data.size());
myFile.close();

int size = data.size();
ifstream input("data.bin", ios::binary);
input.read(reinterpret_cast<char*> (&data[0]), sizeof(cv::Point3f)*size);

This always terminates with "debug assertion failed": "vector subscript out of range".

Is this not possible then? My priority here is speed. I want to read and write as fast as possible. (so binary files are needed).

Well, you're writing data into elements of a vector that simply do not exist.

This approach is not going to work. Use std::copy and std::back_inserter instead! I don't know enough about the layout of cv::Point3f to feel comfortable giving you a code example.

However, if I were just reading individual char s from the std::cin stream, then it would look something like this:

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>

int main()
{
   std::vector<char> data;

   std::copy(
      std::istream_iterator<char>(std::cin),
      std::istream_iterator<char>(),         // (this magic is like "end()" for streams)
      std::back_inserter(data)
   );

   std::cout << data.size() << '\n';
}

// Output: 3

( live demo )

You may use this as a starting point to read in chunks of sizeof(cv::Point3f) instead, and perform the necessary conversions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM