std::vector<bool>
Stop.
A std::vector<bool>
is... not. std::vector
has a specialization for the use of the type bool
, which causes certain changes in the vector
. Namely, it stops acting like a std::vector
.
There are certain things that the standard guarantees you can do with a std::vector
. And vector<bool>
violates those guarantees. So you should be very careful about using them.
Anyway, I'm going to pretend you said vector<int>
instead of vector<bool>
, as the latter really complicates things.
Copying element by element is highly inefficient in case of a really large vector.
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 T
type is convertible to the destination T
, then this is works just fine:
vector<Tnew> vec_new(vec_old.begin(), vec_old.end());
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:
std::vector<int> newVec(oldVec.size());
That's bad. That will allocate a buffer of the proper size, but it will also fill it with data. Namely, default-constructed int
s (int()
).
Instead, you should do this:
std::vector<int> newVec;
newVec.reserve(oldVec.size());
This reserves capacity equal to the original vector, but it also ensures that no default construction takes place. You can now push_back
to 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.