Skip to main content
GameDev.net gamedev.net
🔒 Locked

std::vector Handling Function Not Working

Started by jtmerchant Nov 6, 2004 at 11:10 PM 2 replies 450+ views
Original Post
jtmerchant
jtmerchant
I'm having a problem with my std::vector function that is supposed to clear certain information:

int UserInterface::ClearButton()  {
	std::vector<void*>::iterator i=data.begin();
	std::vector<int>::iterator i2=dataType.begin();
	for(;i != data.end();i++,i2++)  {
		if(*i2 & UIENT_BUTTON)  {
			data.erase(i);
			dataType.erase(i2);
		}
	}
	return 1;
}
My defines are:
#define UIENT_BLANK		0x00010000
#define UIENT_SPRITE	0x00020000
#define UIENT_BUTTON	0x00040000
#define UIENT_TEXTA		0x00080000
#define UIENT_MOUSE		0x00110000
#define UIENT_LIST		0x00120000


#define UIENT_TEXTURE	0x00000001
#define UIENT_POSITION	0x00000002

#define UIENT_TEXTB		0x00000004
#define UIENT_TEXTB1	0x00000010
#define UIENT_TITLE		UIENT_TEXTB1
#define	UIENT_TEXTB2	0x00004444
#define UIENT_ENTRY		0x00001110

#define UIENT_RECT		0x00000008
#define UIENT_ACTION	0x00000011
#define UIENT_TYPE		0x00000012
#define UIENT_COLOR		0x00000014
#define UIENT_WIDTH		0x00000102
A possible value for something in the std::vector dataType might consist of (UIENT_BUTTON | UIENT_RECT). For some reason unknown to me, some parts of the vector that have UIENT_BUTTON in them (like (UIENT_BUTTON | UIENT_RECT)) don't get erased. That is to say, some of them do and some don't.
SiCrane
SiCrane
What's probably happening is that when you call erase() on the vectors, everything gets shifted up by one, and then you increment the iterators, skipping the next element. This means that if two elements satisfy your criteria in a row, the second one won't be deleted. To fix, either don't increment the iterators upon erasure, or try to get your algorithm to work with std::remove_if() or a related function.
Fruny
Fruny
Calling erase() invalidates your iterator. Use the return value from the call instead of unconditionally incrementing it.

while(i != data.end())  {   if(*i2 & UIENT_BUTTON)     {      i = data.erase(i);      i2 = dataType.erase(i2);   }   else   {      ++i;      ++i2;   }}
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
jtmerchant
jtmerchant
Oh.. didn't realize that. Okay it works now. Thanks alot. (Oi! Been working on this bug for a week!)

EDIT::SiCrane- I was still working on a post before I saw yours. I just used i-- and i2-- in the if statement. (Not that it really matters.)

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.