What is the fastest way (if there is any other) to convert a std::vector from one datatype to another (with the idea to save space)? For example:
std::vector<unsigned short> ----> std::vector<bool>
we obviously assume that the first vector only contains 0s and 1s. Copying element by element is highly inefficient in case of a really large vector.
Conditional question:
If you think there is no way to do it faster, is there a complex datatype which actually allows fast conversion from one datatype to another?
Stop.
A
std::vector<bool>is… not.std::vectorhas a specialization for the use of the typebool, which causes certain changes in thevector. Namely, it stops acting like astd::vector.There are certain things that the standard guarantees you can do with a
std::vector. Andvector<bool>violates those guarantees. So you should be very careful about using them.Anyway, I’m going to pretend you said
vector<int>instead ofvector<bool>, as the latter really complicates things.Only if you do it wrong.
Vector casting of the type you want needs to be done carefully to be efficient.
If the the source
Ttype is convertible to the destinationT, then this is works just fine:Decent implementations should recognize when they’ve been given random-access iterators and optimize the memory allocation and loop appropriately.
The biggest problem for non-convertible types you’ll have for simple types is not doing this:
That’s bad. That will allocate a buffer of the proper size, but it will also fill it with data. Namely, default-constructed
ints (int()).Instead, you should do this:
This reserves capacity equal to the original vector, but it also ensures that no default construction takes place. You can now
push_backto your hearts content, knowing that you will never cause reallocation in your new vector.From there, you can just loop over each entry in the old vector, doing the conversion as needed.