5

我有一个代码,在函数的末尾,我需要从 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]);

有没有更好的方法来做到这一点?

谢谢你。

4

2 回答 2

4

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

使用copy_n

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

复制

std::copy( myArrayInt.begin(), myArrayInt.end(), myArrayDouble.begin() );
于 2014-02-28T14:05:15.350 回答
3

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

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));
于 2014-02-28T14:05:23.290 回答