I am using the below code snippet to pass vector of type "uint8_t" to std::fill()
size_t actual_size = 10;
std::vector<uint8_t> response;
std::fill(response.begin(), response.end() actual_size, 0);
But i am getting the below warnings.
message : see reference to function template instantiation 'void std::fill<std::_Vector_iterator<std::_Vector_val<std::_Simple_types<_Ty>>>,int>(const _FwdIt,const _FwdIt,const int &)' being compiled
with
[
_Ty=uint8_t,
_FwdIt=std::_Vector_iterator<std::_Vector_val<std::_Simple_types<uint8_t>>>
]
warning C4244: '=': conversion from 'const _Ty' to 'unsigned char', possible loss of data
with
[
_Ty=int
]
How to resolve this warning.
CodePudding user response:
The reason you are getting the warning is because when filling 0
(an int
) to a vector<uint8_t>
, you are implicitly converting an int
to an uint8_t
, which can potentially have data loss if the original int
is not in the valid range of uint8_t
.
To solve it, you can either create a uint8_t
directly, or manually cast the int
to uint8_t
.
Also, when you do:
std::fill(vec.begin(), vec.end() some_size, some_value)
You are literally filling elements pass the end iterator, without resizing the vector, which is likely not what you wanted.
Instead, you should use fill_n
to specify the number of element to fill, and use back_inserter
to push it to the vector:
std::fill_n(std::back_inserter(vec), some_size, some_value);
Or you can simply initialize the vector with the appropriate data filled:
std::vector<std::uint8_t> vec(some_size, some_value);
Or even zero initialize them, since you were going to assign them to 0
s:
std::vector<std::uint8_t> vec(some_size);