Skip to main content
gamedev.net
🔒 Locked

Map/iterator question

Started by sirSolarius 1 reply 300+ views
Original Post
sirSolarius
sirSolarius
Ok, I''m getting a pop-up error when this code is called:
void MemoryManager::checkMemory()
{
	std::map<char*, CImage*, ltstr>::iterator iter=m_textures.begin();
	std::map<char*, CImage*, ltstr>::iterator ender=m_textures.end();

	while(iter != ender)
	{
		if(! (iter->second->isLive()) )	// if nothing points to the texture

		{
			
			CImage *temp=iter->second;
			
			// erase the texture from OpenGL

			temp->Destroy();
			m_textures.erase(iter);
			//then delete the heap memory

			delete temp;
		}
		iter++;
	}
}
The code hangs on "m_textures.erase(iter)". If that line is omitted, the function works perfectly. The adding code is as follows:
TexPtr MemoryManager::LoadTexture(char *szFilename)
{
	// First, check if the texture exists

	if(m_textures.find(szFilename) != m_textures.end())
	{
		return(TexPtr(m_textures[szFilename]));		// if so, return a MemPtr to it

	}
	else						// if not

	{
		m_textures[szFilename]=new CImage();
		CImage *temp=m_textures[szFilename];

		if(!temp->Load(szFilename))		// Load the new texture

		{
			MessageBox(NULL, szFilename, "Error Loading Texture File!!   .", MB_OK);
			PostQuitMessage(0);
		}
		return (TexPtr(temp));		// return a MemPtr to it

	}
}
Houdini
Houdini
The problem is the erase() invalidates the iterator. Try changing your code to this:


void MemoryManager::checkMemory()
{
std::map<char*, CImage*, ltstr>::iterator iter=m_textures.begin();
std::map<char*, CImage*, ltstr>::iterator ender=m_textures.end();

while(iter != ender)
{
if(! (iter->second->isLive()) ) // if nothing points to the texture

{

CImage *temp=iter->second;

// erase the texture from OpenGL

temp->Destroy();
m_textures.erase(iter++);
//then delete the heap memory

delete temp;
}
else
{
iter++;
}
}
}



- Houdini
Houdini
sirSolarius
sirSolarius

while(iter != ender)
{
if(! (iter->second->isLive()) ) // if nothing points to the texture

{
// make a temp value for the next item, since erase invalidates the iterator

std::map<char*, CImage*, ltstr>::iterator tempI=iter;
tempI++;

CImage *temp=iter->second;

// erase the texture from OpenGL

temp->Destroy();
// remove it from the map

m_textures.erase(iter);
//then delete the heap memory

delete temp;

// now move onto the next value

iter=tempI;
}
else
iter++;
}


Works great now! Thanks!

Topic Locked

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

Sign in to reply to this topic.