Re: std::hash_map question (was re: replacing unsigned char * with CString)
On Wed, 12 Jul 2006 15:57:24 GMT, "David Ching" <dc@remove-this.dcsoft.com>
wrote:
Having gotten used to the MFC collection classes, the standard library is a
bit strange to me. For example, I declare:
hash_map <HWND, MyObject *> m_MyObjects; // map HWND and MyObject
pointers.
To see if a mapping exists for hwnd (a specific HWND):
if ( m_MyObjects[hwnd] != NULL ) // returns TRUE if hwnd has an
associated (MyObject *)
BUT, this line will ADD AN ELEMENT mapping hwnd to NULL (I think), if hwnd
is not in the map! So when I iterate m_MyObjects, hwnd is present. Why
does simply querying the map for an item cause a new entry in the map to be
added? That's not how MFC maps work, nor what I was expecting.
I wouldn't call that a query; it's really an access in service of a query.
If you want to determine if an item is present, use the find member, e.g.
if (m.find(x) != m.end()) ...
Note that the standard associative containers allow you to say the
following when m[x] doesn't exist:
m[x] = y;
f(m[x]);
Rather than throw an exception if m[x] doesn't exist, which is the only
reasonable alternative, the associative containers add a default object to
the container. If you use this feature, your mapped type must have a
default ctor.
The thing I found most surprising about the maps is that their insert
function doesn't update an existing item. Instead, if the item exists, they
leave the map unchanged, signifying that the insertion didn't take place by
returning a std::pair whose "second" member is false.
--
Doug Harrison
Visual C++ MVP