如何在C ++中正确地静态转换向量?

时间:2014-02-28 13:43:44

标签: c++ stdvector stdarray

我有一个代码,在函数结束时我需要从int转换为double数组的所有元素,以便在退出函数之前能够执行最终的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]);

有没有更好的方法呢?

谢谢。

2 个答案:

答案 0 :(得分:3)

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

使用copy_n

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

copy

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

答案 1 :(得分:1)

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

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));