LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   signed/unsigned int and vector::size() (https://www.linuxquestions.org/questions/programming-9/signed-unsigned-int-and-vector-size-601815/)

[KIA]aze 11-23-2007 01:49 AM

signed/unsigned int and vector::size()
 
I'm currently having a bug I don't quite understand:

The variable animationSheet is declared as follows:
Code:

vector<spriteSheet *> animationSheet;
The first version of the problematic code was like this:
Code:

for (int idx = 0; idx < animationSheet.size(); idx++)
{
  delete animationSheet[idx];
}

It worked, but during compilation, there was this warning:
Quote:

warning: comparison between signed and unsigned integer expressions
So we changed the code to this:
Code:

for (unsigned int idx = 0; idx < animationSheet.size(); idx++)
{
  delete animationSheet[idx];
}

This however caused problems in the program because spriteSheets were deleted that shouldn't have been deleted (with numbers like 65536 for example)

I changed the code like this:
Code:

int idx=0;
for ((unsigned int) idx; idx < animationSheet.size(); idx++)
{
  delete animationSheet[idx];
}

But it has no effect.

I would like to understand what's really going on here and how to have it work without warnings.

vector::size seems to return a size_type.
Which I suppose is the same as size_t, i.e an unsigned integer.

int seems to be a signed int by default.

What happens in each case during the comparison?
And how does the "animationSheet[idx]" use idx? as signed or unsigned integer?

dmail 11-23-2007 06:19 PM

There are a number of ways of doing this without getting a warning.
First method is to use a smart pointer class and then you never have to worry about cleaning up pointers.

Second method is to not use pointers and instead use instances of classes( yet this may not be what you want).

Third use the for_each function
Code:

#include <algorithm>
#include <vector>

template <typename T>void deleter (T* t)
{
  delete t;
}

...
std::for_each (animationSheet.begin(), animationSheet.end(), deleter<spriteSheet>);
animationSheet.clear();
...

Forth use the iterator class
Code:

...
for(std::vector<spriteSheet*>::iterator i = animationSheet.begin();
i != animationSheet.end(); ++i)
{
        delete *i;
}
animationSheet.clear();
...

And the last one that I can think of at the moment is to use size_type as you pointed out
Code:

...
for (std::vector<spriteSheet*>::size_type i = 0; i < animationSheet.size(); ++i)
{
  delete animationSheet[i];
}
animationSheet.clear();
...



All times are GMT -5. The time now is 07:36 PM.