Iterate trough std::map

Started by
4 comments, last by johan_swe 20 years, 3 months ago
My program crashes when I iterate through a std::map. m_pTextureLoader is a pointer to an object that loads textures (the file names) from directories and stores them in a std::map. The key in the map is the directory of the loaded texture and the second, a std::vector, contains strings for every available texture in that directory. The texture loader has a function that returns a pointer to the texture map. When I iterate through the map, the program crashes when it reaches it++ (which is after the first directory).

typedef std::map<std::string, std::vector<std::string> >	TEXTUREFILENAMES;

m_pTextureFileNames = m_pTextureLoader->GetTextureFileNames();

//for each directory

for(TEXTUREFILENAMES::const_iterator it = m_pTextureFileNames->begin(); it != m_pTextureFileNames->end(); it++)
{
//for each texture

for(DWORD c = 0, d = 0; d < it->second.size(); c++, d++)
{
//Do something

}
}

Advertisement
Make sure that "do something" does not erase the iterator or delete the map.


[edited by - DrPizza on January 6, 2004 4:10:22 PM]
char a[99999],*p=a;int main(int c,char**V){char*v=c>0?1[V]:(char*)V;if(c>=0)for(;*v&&93!=*v;){62==*v&&++p||60==*v&&--p||43==*v&&++*p||45==*v&&--*p||44==*v&&(*p=getchar())||46==*v&&putchar(*p)||91==*v&&(*p&&main(0,(char**)(--v+2))||(v=(char*)main(-1,(char**)++v)-1));++v;}else for(c=1;c;c+=(91==*v)-(93==*v),++v);return(int)v;}  /*** drpizza@battleaxe.net ***/
No, it doesn''t change the iterator or the map.
Hum, could it be that you have it++ ?
try having ++it instead or otherwise the first iterator might get wrong?

Not sure why... but try that?
I think that the for loop might mess it up; on the last iteration, i.e. end-1, the condition is still fulfilled. But on the next step, it gets incremented, so on the last loop, you''re actually modifying a non-existent entry.

To simplify everything, I just use
while( it != m_pTextureFilesNames.end() ) {  // code  ...  // next iteration  ++it;}   
quote:Original post by psykr
I think that the for loop might mess it up; on the last iteration, i.e. end-1, the condition is still fulfilled. But on the next step, it gets incremented, so on the last loop, you''re actually modifying a non-existent entry.


The loop is correct.
"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

This topic is closed to new replies.

Advertisement