How to properly static cast a vector in C++?

喜欢而已 提交于 2021-01-27 07:11:26

问题


I have a code in which at the end of a function I need to cast from int to double all the elements of an array in order to being able to do a final push_back before exiting the function. The code I have right now is:

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

It works properly, but I do not feel comfortable about the lines:

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

Is there any better way of doing this?

Thank you.


回答1:


You can use a function from algorithm.

With copy_n :

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

or with copy :

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



回答2:


This can be written with less code, but it is explicit.

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


来源:https://stackoverflow.com/questions/22096834/how-to-properly-static-cast-a-vector-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!