Vector size and int

Started by
3 comments, last by BitMaster 8 years, 5 months ago

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...");
}

Advertisement
I don't get it. Why can't you just do "if (poolIndex < pool.size())" and be done? Also, why aren't you building with high-level warnings and warnings-as-errors?

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

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.

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.

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.

This topic is closed to new replies.

Advertisement