Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert explicitly when constructing a vector copy with elements of different type?

I'm making a copy q of vector v, but element types are different and implicitly convertible:

vector<int>   v = {1, 2, 3, 2};
vector<float> q(v.begin(), v.end());

This code compiles with a template barf (warning) about type conversion. What is the way to make conversion explicit and avoid the warning?

EDIT

I'm using Visual Studio 2013 with warning level 3 (/W3). Here is the top of warning message:

warning C4244: 'initializing' : conversion from 'int' to 'float', possible loss of data ...

like image 672
Paul Jurczak Avatar asked Aug 28 '14 05:08

Paul Jurczak


1 Answers

The C++ Draft Standard (N3337) has this to say about floating point conversion.

4.9 Floating-integral conversions [conv.fpint]

2 A prvalue of an integer type or of an unscoped enumeration type can be converted to a prvalue of a floating point type. The result is exact if possible. If the value being converted is in the range of values that can be represented but the value cannot be represented exactly, it is an implementation-defined choice of either the next lower or higher representable value. [ Note: Loss of precision occurs if the integral value cannot be represented exactly as a value of the floating type. — end note ] If the value being converted is outside the range of values that can be represented, the behavior is undefined.

The warning is understandable if the range of values of an int is outside the range of values of a float.

If the range of value of an int is within the range of values of a float, the compiler warning is overly zealous.

I would try @Nawaz's suggestion to get rid of the compiler warning:

std::transform(begin(v), end(v),
    std::back_inserter(q), [](int i) { return static_cast<float>(i); });
like image 54
R Sahu Avatar answered Oct 28 '22 13:10

R Sahu