I can construct data on Line 19 from vvp.at(0) if I know the size of vf.
#include <iostream>
#include <vector>
typedef void* VoidPointer;
typedef std::vector< float > VF;
typedef std::vector< VoidPointer > VVP;
int main(int argc, char** argv)
{
VF vf;
vf.push_back(13.0f);
vf.push_back(14.0f);
vf.push_back(15.0f);
vf.push_back(16.0f);
VVP vvp;
vvp.push_back( (VoidPointer)const_cast<float *>( &(vf.front()) ) );
VF data ( static_cast< float* >( vvp.at(0) ),
static_cast< float* >( vvp.at(0) ) + vf.size() );
std::cout << "data.size() is " << data.size() << std::endl;
for(VF::const_iterator i = data.begin(); i != data.end(); ++i)
{
std::cout << "data contains " << *i << std::endl;
}
return 0;
}
Leaving aside whether this is sensible (the example is contrived) I’d like to know how to cast vvp.at(0) to a std::vector<float> if I didn’t know the size of vf. I’m thinking along the lines of something like:
std::vector<float> data( *static_cast< std::vector<float>* >( vvp.at(0) ) );
But that causes the program to termintate with std::bad_alloc, I don’t mind copying if need be.
That is not a cast from
vvp.at(0)to a vector, it’s a copy of an array of floats into a new vector. And you can’t copy it without knowing the length. You only saved a pointer to the first element, so the information was lost.You could make
std::vector<std::pair<VoidPointer, size_t> > VVPand save both&vf.front()andvf.size()(or start and end pointers, if you prefer).You could make
std::vector<VF *>and store pointers to vectors (i.e.vvp.push_back(&vf)) and now there’s no casting at all.Edit: In case you didn’t realize: The pointer
&vfis unrelated to&vf.front().vfis a structure which contains the pointer&vf.front()(or a way to get it). There’s no information in just the address&vf.front()to let you find&vf.