0
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).

6
  • When you are reading the binary file how do you know how many elements were saved to it? The usual practice is to save it as a file 'header'. During the read operation you read the size first, then load however many items follow. Commented May 21, 2015 at 14:30
  • You need to create data big enough to hold the contents of the file. Commented May 21, 2015 at 14:30
  • 2
    Have you initialized data to the correct length before reading from file? Double check that data.size() is actually nonzero, otherwise data[0] will be an invalid access. Check data.size() both before writing and reading. Commented May 21, 2015 at 14:30
  • len = readLengthOfVector(); data.resize(len); readData(data,len); This pseudocode shows you how it usually looks like. Commented May 21, 2015 at 14:31
  • 1
    You need to write the length of the vector (number elements) before writing the vector contents. Then, when reading it back in, you have to read the number of elements you are about to read and do the psuedocde that @BitTickler just posted. Commented May 21, 2015 at 14:46

1 Answer 1

2

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 chars 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.