Search code examples
c++castingvector

Safe to assign vector<int> to vector<double>?


To initialize variables for a certain computation I have to assign them values from an integer array. So I do:

vector<double> vd;
int ai[N]; // Filled somewhere else

vd.assign(ai, ai+N);

This works under gcc 4.6.1 Linux. But is it always correct? Or should I return to the evergreen:

vd.resize(N);
for(int i=0; i < N; ++i) vd[i] = (double)ai[i];

Thanks for clarifying!


Solution

  • I think this is safe, since assign is a template. See http://www.cplusplus.com/reference/stl/vector/assign/. The implementation assigns doubles from ints, which basically is not different to your other solution. Checking the header in /usr/include/c++/4.6/bits/stl_vector.h it seems the constructer and assign both call the same internal function, _M_assign_dispatch.