I have some code that makes some computations and then returns a lot (thousands or even hundreds of thousands) of vectors
of vectors
of doubles
(matrices). These values are already rounded to the nearest integer and will never exceed the max size of a byte. The matrices will be flattened to one dimensional vectors
and then written as binary data to a file. However, I don't want to store these values as doubles
, since they would take up more space. They need to be stored as chars
but the code that returns them will always give me doubles, so I was wondering what is the fastest way of casting all the doubles
to chars
.
I'm specifically looking for a way to convert the vectors
of one type to another, because vectors are easy to be written to files.
Have you tried std::copy
or std::transform
? Seems like it should be very straightforward.
You can cast your vector without problem in this mode:
const char* VectToChar = (char*)&Vector[0];
In the following code you can find a full example. Warning this code is valid only for vector data reading and not for writing!
#include <stdio.h>
#include <vector>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
vector<double> Vector;
Vector.push_back(10.2);
Vector.push_back(15.2);
// You can use this method only for data reading, no writing!!
const char* VectToChar = (char*)&Vector[0];
// Test
double d0 = *((double*)VectToChar);
double d1 = *((double*)(VectToChar+sizeof(double)));
printf("%f, %f", d0, d1);
return 0;
}
I ended up writing a char
version of the last method in the calculation. Easier than having to copy or doing more complex stuff.
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.