Archived

This topic is now archived and is closed to further replies.

Iterate trough std::map

This topic is 5093 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

}
}

Share this post


Link to post
Share on other sites
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;
}

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites