4

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!

Machavity
  • 30,841
  • 27
  • 92
  • 100
mvalle
  • 265
  • 3
  • 8

2 Answers2

3

Implicit conversion will take place so it is safe. And why not initializing vector during its construction:

std::vector<double> vd(ai, ai + N);
Bojan Komazec
  • 9,216
  • 2
  • 41
  • 51
0

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.

hochl
  • 12,524
  • 10
  • 53
  • 87