finding and erasing an element from a vector stored in a map

Started by
2 comments, last by Smit 17 years, 6 months ago
For my message passing class I have a std::map which indexes a std::string message type to a std::vector of target task pointers. Typedef'd like so:

typedef std::vector< ITask* > TaskList;
typedef std::map< std::string, TaskList > MsgTargetMap;
My RegisterTarget() works great, but my UnregisterTarget() compiles but causes an assert "vector erase iterator outside range". Anyway heres the code:

bool Messenger::UnregisterTarget( ITask* pTarget, std::string sMsgType )
{
	MsgTargetMap::iterator it_tm; 
	TaskList::iterator     it_tl;

        TaskList               tl;

        // Try to find the message type in the map.
	it_tm = m_TargetMap.find( sMsgType );

        // If it doesn't exist send a warning to the log.
	if( it == m_TargetMap.end() )
	{
		Log::Get()->LogMessage( "Attempting to remove target from non-existing message!", "Messenger", LOG_MSGTYPE_WARNING, LOG_LEVEL_NORMAL );
		return false;
	}
        // If it does exist...
	else
	{
                // Get a copy of the vector.
		tl = (*it).second;

                // Find the task pointer to remove.
		tl_it = std::find( tl.begin(), tl.end(), pTarget );

                // Erase the found item from the vector.
		tl.erase( tl_it );

                // Put the modified vector back into the map.
		(*it).second = tl;
	}

	return true;
}

I thought you could use iterators as a parameter for erase? Thanks!
Advertisement
i don't really read your code, as i'm not that c++ fluent anymore anyways, but i have a question:
would std::multi_map work for you? it can store several ITask* per std::string message in one go.

just an idea.
If that's not the help you're after then you're going to have to explain the problem better than what you have. - joanusdmentia

My Page davepermen.net | My Music on Bandcamp and on Soundcloud

If the pointer is not in the vector, then you're passing the end() iterator to the erase method. This will raise an assert in debug mode, so make sure you handle that case.
ITGER:

Just checked, the iterator is at end(), but the pointer is inside of the vector :/

davepermen:

I'll look into the multimap [smile].

This topic is closed to new replies.

Advertisement