ChatGPT解决这个技术问题 Extra ChatGPT

C++ convert vector<int> to vector<double>

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?


H
Harry

Use std::vector's range constructor:

std::vector<int> intVec;
std::vector<double> doubleVec(intVec.begin(), intVec.end());

So, you could also use the std::copy(...) function then? Could you add that to the answer?
@Lex: copy(v_int.begin(), v_int.end(), back_inserter(v_float));, or v_float.resize(v_int.size()); copy(v_int.begin(), v_int.end(), v_float.begin());
bad idea, because the constructor version will presize the vector by using the iterator category to note that those are random access iterators and then reserving enough space. Resizing prior to copy is a wasteful zero initialization.
@MichaelGoldshteyn I don't understand - if you don't specify the size beforehand, then it will be resized automatically whenever the capacity is exceeded (which copies all the elements over and over again). Okay, this is amortized linear time, but I bet that's still a lot slower than a single 0-initialization. Am I missing something about your argument?
@Algoman see 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().
Y
Yas

Use std::transform algorithm:

std::transform(intVec.begin(), intVec.end(), doubleVec.begin(), [](int x) { return (double)x;});