I am trying to use std::count over std::vector as following:
int count = std::count( stdVector.begin(), stdVector.end(), "element" );
On windows, it gives the following compiler error.
error C4244: 'initializing' : conversion from '__int64' to 'int', possible loss of data
If I change the code as following on Windows
compiler does not appear.
auto count = std::count( stdVector.begin(), stdVector.end(), "element" );
However, now I face the following error on linux for the above change.
error: ISO C++ forbids declaration of 'count' with no type
How would I use std::count
which will get build on both the platform without any error?
There are two things that can conflict differently in different environments:
The first is auto
as a deduced type is a C++11 feature. May be the linux compiler does not have it as a default (just use -std=c++11
, and if it does not have it, upgrade!)
The other is that the return type of std::count is size_t
, not int
, and size_t
to int
conversion may lose data depending on on how size_t
is defined (there is at least a signed / unsigned mismatch and eventually a different in size of the two types, like 32 bit for int
and 64 bit for size_t
).
The reason you get this warning is that on a 64 bit build, the standard containers use 64 bit values for size types, and implicitly converting a 64 bit value (e.g. size_t
) to a 32 bit value (e.g. int
) can lose data.
The actual data type returned by the count
function, which in this case would be std::vector<T>::difference_type
, is probably the best type to use if your compiler doesn't support auto
. Using size_t
would probably work without warning as well, and is a lot shorter to type.
Alternatively, if you're not bothered by the risk of data loss (e.g. are never planning to have more than 2^32-1 objects in the container) you can simply cast the warning away:
int count = static_cast<int>( std::count(stdVector.begin(), stdVector.end(), "element") );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With