如何在C++中正确静态转换矢量



>我有一个代码,在函数结束时,我需要从 int 转换为数组的所有元素的双倍,以便能够在退出函数之前进行最后的push_back。我现在的代码是:

template <class T, size_t dims> class A {
    typedef typename std::array<int, dims> ArrayInt;
    typedef typename std::array<double, dims> ArrayDouble;
    typedef typename std::vector <ArrayDouble> VectorDouble;
/* ...*/
foo() {
   /*  ...*/
   ArrayInt myArrayInt;
   ArrayDouble myArrayDouble;
   VectorDouble myVectorDouble;
    /* Initialize myArrayInt 
    Do some other stuff */
    for (int i = 0; i < dims; ++i) 
        myArrayDouble[i] = static_cast<double>(myArrayInt[i]);
    myVectorDouble.push_back(myArrayDouble);
    }
}

它工作正常,但我对这些台词感到不舒服:

for (int i = 0; i < dims; ++i) 
    myArrayDouble[i] = static_cast<double>(myArrayInt[i]);

有没有更好的方法?

谢谢。

您可以使用算法中的函数。

copy_n :

std::copy_n( myArrayInt.begin(), dims, myArrayDouble.begin() );

或带副本:

std::copy( myArrayInt.begin(), myArrayInt.end(), myArrayDouble.begin() );

这可以用更少的代码编写,但它是明确的。

ArrayInt myArrayInt;
ArrayDouble myArrayDouble;
VectorDouble myVectorDouble;
/* Initialize myArrayInt 
Do some other stuff */
using std::transform;
using std::copy;
using std::begin;
using std::end;
// with explicit conversion
auto to_double = [](const int i) { return double{i}; };
transform(begin(myArrayInt), end(myArrayInt), begin(myArrayDouble),
    to_double);
// with implicit conversion
copy(begin(myArrayInt), end(myArrayInt), begin(myArrayDouble));

最新更新