Search code examples
c++castingstdarray

What is the easiest way to fill std::array of int with elements of std::array of double with proper casting?


I want to use std::array<double, 4> in function that uses std::array<int, 4>?

So, what is the easiest / shortest(both of them) way to achieve that.

E.g.

#include <array>
#include <iostream>

void printInts(std::array<int, 4> someInts) {
    for(int someInt : someInts) {    
        std::cout << someInt << std::endl;
    }
}

std::array<double, 4> someDoubles{1.1, 2.2, 3.3, 4.4};

int main() {
    printInts(someDoubles); // of course it doesn't work
    return 0;
}

Thanks a lot for every help ;)

P.S

1
2
3
4

will be expected output of course.


Solution

  • If you can't change the function PrintInts, then you could just create an int version of the array, and call the function with that:

    std::array<int, 4> ints;
    std::copy(std::begin(someDoubles), std::end(someDoubles), std::begin(ints));
    printInts(ints);
    

    Be aware that converting from double to int could lose precision due to the narrowing conversion. This could even result in UB if the converted double value cannot be represented by an int.

    Here's a demo.