将 std::vector<int> intVec
转换为 std::vector<double> doubleVec
的好方法是什么。或者,更一般地说,转换两个可转换类型的向量?
使用 std::vector
的范围构造函数:
std::vector<int> intVec;
std::vector<double> doubleVec(intVec.begin(), intVec.end());
使用 std::transform
算法:
std::transform(intVec.begin(), intVec.end(), doubleVec.begin(), [](int x) { return (double)x;});
std::copy(...)
函数吗?您可以将其添加到答案中吗?copy(v_int.begin(), v_int.end(), back_inserter(v_float));
或v_float.resize(v_int.size()); copy(v_int.begin(), v_int.end(), v_float.begin());
std::distance()
“如果它是随机访问迭代器,则该函数使用 operator- 来计算它。否则,该函数重复使用递增运算符 (operator++)。”所以在这种情况下,可以通过减去迭代器来找到元素的数量。标准库是否实现为使用 std::distance 作为初始 reserve() 是另一个问题,但 godbolt.org/z/6mcUFh 至少包含对 std::distance() 的调用。