Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialization of vector<float> error during uniform initialization

Tags:

c++11

When I compile this in Visual Studio 2015 I get an error: error C2398: Element '1': conversion from 'double' to 'float' requires a narrowing conversion

vector<float> v {2.46, 2.58, 2.0, 2.25, 3.0 };

But this works

vector<float> v{ (float)2.46, (float)2.58, (float)2.0, (float)2.25, (float)3.0 };

Is there an elegant solution to this code so I don't have to case all my inputs to float? Maybe tweaking initializer_list ?

like image 905
Damian Avatar asked Mar 23 '26 23:03

Damian


1 Answers

shamelessly stealing the comment from igor-tandetnik:

vector<float> v {2.46f, 2.58f, 2.0f, 2.25f, 3.0f };

And then complementing it to make it an answer:

The literal 0.42 has the type double. To have a literal of type float you need the f suffix: 0.42f.

You can read more (well... it's not that much) about integer literals and floating point literals

like image 57
bolov Avatar answered Mar 26 '26 14:03

bolov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!