简体   繁体   English

将矢量写入和读取二进制文件

[英]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! 改用std::copystd::back_inserter I don't know enough about the layout of cv::Point3f to feel comfortable giving you a code example. 我对cv::Point3f的布局cv::Point3f无法为您提供代码示例。

However, if I were just reading individual char s from the std::cin stream, then it would look something like this: 但是,如果我只是从std::cin流中读取单个char ,那么它将看起来像这样:

#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. 您可以以此为起点来读取sizeof(cv::Point3f)块,并执行必要的转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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