Sign in to follow this  
Smit

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

Recommended Posts

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!

Share this post


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

Share this post


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

Share this post


Link to post
Share on other sites
ITGER:

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

davepermen:

I'll look into the multimap [smile].

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this