What is a good clean way to convert a std::vector<int> intVec
to std::vector<double> doubleVec
. Or, more generally, to convert two vectors of convertible types?
Use std::vector
's range constructor:
std::vector<int> intVec;
std::vector<double> doubleVec(intVec.begin(), intVec.end());
Use std::transform
algorithm:
std::transform(intVec.begin(), intVec.end(), doubleVec.begin(), [](int x) { return (double)x;});
Success story sharing
std::copy(...)
function then? Could you add that to the answer?copy(v_int.begin(), v_int.end(), back_inserter(v_float));
, orv_float.resize(v_int.size()); copy(v_int.begin(), v_int.end(), v_float.begin());
std::distance()
"If it is a random-access iterator, the function uses operator- to calculate this. Otherwise, the function uses the increase operator (operator++) repeatedly." So in this case the amount of elements could be found by subtracting the iterators. Whether the standard library is implemented to use std::distance for an initial reserve() is another question, but godbolt.org/z/6mcUFh at least contains a call to std::distance().