Re: hash_map : what is wrong?
"K?r?at" <xx@yy.com> ha scritto nel messaggio
news:%23JKVVw3vIHA.2064@TK2MSFTNGP05.phx.gbl...
The code below sometimes results access violation at hash_map::erase :
char * popItem (int nKey)
{
char * item = NULL;
stdext::hash_map <int, char * >::iterator hmIterator =
m_hmItemMap.find (nKey);
It seems that you did follow-up neither Brian nor me.
However, I still believe that if you use std::string instead of raw char*
pointers, you will have no access violation.
You may consider the following simple example code, which uses std::string
instead of char* (I renamed your popItem() method as Extract()):
<code>
#include <hash_map>
#include <string>
class IntToString
{
public:
void Insert( int key, const std::string & value )
{
typedef std::pair< int, std::string > IntStringPair;
m_map.insert( IntStringPair( key, value ) );
}
std::string Extract( int key )
{
std::string item;
IntToStringMap::iterator it = m_map.find( key );
if ( it != m_map.end() )
{
item = it->second;
m_map.erase( key );
}
else
{
// Not in map: throw an exception
throw std::invalid_argument( "Key not presenet in map." );
}
return item;
}
// ...
// ... other members
// ...
private:
typedef stdext::hash_map< int, std::string > IntToStringMap;
IntToStringMap m_map;
};
</code>
Test like this:
<code>
IntToString map;
map.Insert( 1, "January" );
map.Insert( 2, "February" );
map.Insert( 5, "May" );
cout << map.Extract(5) << endl;
cout << map.Extract(1) << endl;
cout << map.Extract(2) << endl;
</code>
HTH,
Giovanni