I have a huge contiguous array x
that I fread
from a file.
How do I drop this chunk into a std::vector<>
? In other words, I prefer to have the result to be in std::vector<>
rather than the array, but I want the resultant C++ code to be as efficient as this plain C-version which drops the chunk right into the array.
From searching around, I think I may have to use placement-new in some form, but I'm uncertain about the sequence of calls and ownership issues. Also, do I need to worry about alignment issues?
I am testing for with T = unsigned
, but I expect a reasonable solution to work for any POD struct.
using T = unsigned;
FILE* fp = fopen( outfile.c_str(), "r" );
T* x = new T[big_n];
fread( x, sizeof(T), big_n, fp );
// how do I get x into std::vector<T> v
// without calling a gazillion push_backs() or copies ?!?
delete[] x;
fclose( fp );