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

I make a copy q vector v , but the element types are different and are implicitly converted:

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

This code is compiled using the type conversion barf (warning) pattern. How to make the conversion explicit and avoid the warning?

EDIT

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

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

+5
source share
1 answer

The C ++ Draft Standard (N3337) project talks about floating point conversion.

4.9 Transforms with a floating integral [conv.fpint]

2 The sign value of an integer type or an unenumerated enumeration type can be converted to a prvalue of a floating-point type. The result is accurate if possible. If the converted value is in the range of values ​​that can be represented, but the value cannot be represented accurately, it is a choice determined by the implementation of either the next lower or higher represented value. [Note: loss of precision occurs if the integral value cannot be represented exactly as a floating-point value. - end note] If the converted value is outside the range of values ​​that can be represented, the behavior is undefined.

The warning is clear if the range of int values ​​is outside the range of a float .

If the range of int values ​​is in the range of a float , the compiler warning is too hard.

I would try the @Nawaz 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); }); 
+3
source

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


All Articles