Is it safe to assign a vector <int> to a vector <double>?

Possible duplicate:
C ++ convert vector <int> to vector <double>

To initialize variables for a specific calculation, I have to assign them values ​​from an integer array. So I:

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 right? 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!

+4
source share
2 answers

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

0
source

An implicit conversion will be performed to be safe. And why not initialize the vector during its construction:

 std::vector<double> vd(ai, ai + N); 
+3
source

All Articles