How do I get rid of this" conversion from 'size_t' to 'long'" error?

vVector.size() gets the size of my vector.

I want to divide the size of my vector into a long variable, longTotal.

longTotal / vVector.size() yields this error:

warning C4267: '=' : conversion from 'size_t' to 'long', possible loss of data

I realize .size() returns a size_t, and it's not a long.  However, I do need to divide the long variable longTotal by the size of the vector...What do I do to get rid of this error?
LVL 1
shaolinfunkAsked:
Who is Participating?
 
trinitrotolueneConnect With a Mentor Director - Software EngineeringCommented:
this is just a warning and is not an error. But this doesnt mean you should ignore it since warnings could provide indications of future errors.

do the following

long vecsize = static_cast<long>(vVector.size());

longtotal/vecsize;
0
 
trinitrotolueneDirector - Software EngineeringCommented:
just to add size_t is always guaranteed to be an integral unsigned type but the number of bits it takes depends on the environment that you are compiling on.
0
 
pgnatyukCommented:
You can do longTotal / (long)vVector.size().

size_t type:
http://www.cplusplus.com/reference/clibrary/cstring/size_t/

size_t is defined in a typedef. In your case it is, probably, unsigned long. So the compiler says that you are dividing a long integer value by an unsigned long.
 
0
 
evilrixSenior Software Engineer (Avast)Commented:
The real solution is stop using the incorrect type when handling the size of STL containers. They all use size_t (well, they actually all use ::size_type but this is generally defined as a size_t) and if you don't use this type yourself you are running the risk of writing non-portable code.

Using a static cast to remove the warning is not a solution it is a work around and is a poor way to handle this! as stated above, "you should ignore it since warnings could provide indications of future errors" and yet a cast is nothing more than a way to tell the compiler to ignore the warning.

http://www.cplusplus.com/reference/stl/vector/
size_type      Unsigned integral type (usually same as size_t)

http://www.cplusplus.com/reference/clibrary/cstring/size_t/
size_t corresponds to the integral data type returned by the language operator sizeof and is defined in the  header file (among others) as an unsigned integral type.

NB. there is nothing in the standard to say it'll be an unsigned long -- it's just guaranteed to be an unsigned integer type.
0
All Courses

From novice to tech pro — start learning today.