title: How can I use fread() on a binary file to read the data into a std::vector?
body: <p>Follow-up question on an earlier <a href="https://stackoverflow.com/questions/15136992/why-does-my-program-crash-when-using-fread-in-the-constructor">question</a> I had, that has been perfectly answered. To quickly recap, I had trouble creating a class holding a huge array (stack overflow error). In the answers, some users recommended I use std::vector instead.</p>
  
  <p>The function to read in the data looks like this:</p>
  
  <pre><code>Test()
  {
     memset(myarray, 0, sizeof(myarray));
     FILE* fstr = fopen("myfile.dat", "rb");
     size_t success= fread(myarray, sizeof(myarray), 1, fstr);
     fclose(fstr);
  }
  </code></pre>
  
  <p>for a myarray which looked like this:</p>
  
  <pre><code>int myarray[45000000];
  </code></pre>
  
  <p>My question is: How can I read this into a preferable:</p>
  
  <pre><code>std::vector&lt;int&gt; myvector;
  </code></pre>
  
  <p>I searched google , and have found multiple answers, usually pointing to the following code:</p>
  
  <pre><code>std::ifstream input("myfile.dat", std::ios::in | std::ifstream::binary);
  std::copy(std::istream_iterator&lt;int&gt;(input), 
       std::istream_iterator&lt;int&gt;(), 
       std::back_inserter(myvector));
  </code></pre>
  
  <p>After implementing this, and when calling myvector.size() I get 16 (for whatever reason), and accessing a vector element leads to an immediate crash for going out of the vector bounds.</p>
  
  <p>So what do I have to do to get this right? I once read somewhere that I could just simply use the "old" method, and then reading the array into the vector, but this seems to defeat the purpose of using the vector in the first place.</p>