How to put a vector in C ++?

I have a code in which at the end of the function I need to drop from int to double all the elements of the array in order to be able to do the final push_back before exiting the function. The code I have 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 correctly, but I don't feel comfortable with the strings:

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

Is there a better way to do this?

Thanks.

+4
source share
2 answers

You can use the function from the algorithm.

With copy_n :

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

or copy :

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

It 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));
+1
source

Source: https://habr.com/ru/post/1529413/


All Articles