• Advertisement
Sign in to follow this  

Vector size and int

This topic is 900 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I kind of ran into a minor snag and was wondering how can I go about comparing a int to the value returned by Vector.size()?

 

My current code will always trigger the top portion of the If statement, because of the int to size_t comparison. So I am a little unsure if I should just cast pool.size() to a int or is there a better way?

 

poolIndex is the current pool item I am using in the pool vector. EG: pool[poolIndex].DoStuff()

 

Current code:

//In init code (pool starts off as having nothing in it)
poolIndex = 0;

if (poolIndex <= pool.size() - 1)
{
	Logger::Verbose("native", "Available space in the pool");
}
else
{
	Logger::Verbose("native", "No free space available. Need to create new space...");
}

Share this post


Link to post
Share on other sites
Advertisement

size_t (the type returned by size() function) is unsigned; subtract 1 from 0 with an unsigned number give you a very large number.  So the comparison that (index < pool.size() - 1) will always return true when size() == 0 (well to be pedantic not always, but pretty much always).  As ApochPiQ is stated, using (index < pool.size()) avoids this problem.

Share this post


Link to post
Share on other sites

Additionally, you should use size_t as the type of your poolIndex and other index or size variables, to avoid signed/unsigned type mismatches and different number of available bits.

Share this post


Link to post
Share on other sites

Additionally, you should use size_t as the type of your poolIndex and other index or size variables, to avoid signed/unsigned type mismatches and different number of available bits.


Well, strictly he should use std::vector<>::size_type, but I don't know of any standard library implementation where that would matter.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement