CMAP 관련자료


Programmers like me, who learnt STL::map before CMap, always think CMap is difficult to use, and always try to use CMap in the way as a STL::map. In this article, I will explain about CMap and what you should do to use it for your own custom classes. And at the end of this article, I will show an example of how to use CMap correctly with CString* (note, I mean CString pointer and not CString :>)

CMap Internal

The first thing to be noted is that CMap is actually a hash map, and not a tree map (and usually a Red-black tree) as STL::map. Shown below is the internal structure of a CMap.

How to declare a CMap

Many people get confused about CMap‘s declaration CMap<KEY, ARG_KEY, VALUE, ARG_VALUE>, why not just CMap<KEY, VALUE>?

In fact, the ultimate data container in CMap is CPair, and the internal of CPair is {KEY, VALUE}. Therefore, CMap will really store a KEY, and not ARG_KEY. However, if you check with the MFC source code, almost all the internal parameters passing within CMap itself is called with ARG_KEY and ARG_VALUE, therefore, using KEY& as ARG_KEY seems always a correct thing, except when:

  1. You are using primitive date types like int, char, where pass-by-value makes no difference (may be even faster) with pass-by-reference.
  2. If you use CString as KEY, you should use LPCTSTR as ARG_KEY and not CString&, we will talk more about this later.

So what should I do to make CMap work with my ClassX

Well, as I mentioned earlier, CMap is a hash map, a hash map will try to get the “hash value” — a UINT — from the key, and use that hash value as the index in the hash table (well, actually it is hash value % hash table size). If more then one key have the same hash value, they will be linked in a linked list. Therefore, the first thing you have to do is to provide a hash function.

CMap will call a templated function HashKey() to do the hashing. The default implementation and specialized version for LPCSTR and LPCWSTR are listed as follows:

Hide Shrink Copy Code

// inside <afxtemp.h>
template<class ARG_KEY>
    // default identity hash - works for most primitive values
    return (DWORD)(((DWORD_PTR)key)>>4);
// inside <strcore.cpp>
// specialized implementation for LPCWSTR
#if _MSC_VER >= 1100
template<> UINT AFXAPI HashKey<LPCWSTR> (LPCWSTR key)
    UINT nHash = 0;
    while (*key)
        nHash = (nHash<<5) + nHash + *key++;
    return nHash;
// specialized implementation for LPCSTR
#if _MSC_VER >= 1100
template<> UINT AFXAPI HashKey<LPCSTR> (LPCSTR key)
    UINT nHash = 0;
    while (*key)
        nHash = (nHash<<5) + nHash + *key++;
    return nHash;

As you can see, the default behavior is to “assume” that the key is a pointer, and convert it to DWORD, and that’s why you will get “error C2440: ‘type cast’: cannot convert from ‘ClassXXX’ to ‘DWORD_PTR'” if you don’t provide a specialized HashKey() for your ClassX.

And because MFC only has specialized implementations for the LPCSTR and LPCWSTR, and not for CStringA nor CStringW, if you want to use CString in CMap, you have to declare CMap<CString, LPCTSTR....>.

OK, now you know how CMap calculates the hash value, but since more than one key may have the same hash value, CMap needs to traverse the whole linked list to find the one with exactly the same key “content“, not only with the same “hash value“. And when CMap does the matching, it will call CompareElements(), another templated function.

Hide Copy Code

// inside <afxtemp.h>
// noted: when called from CMap,
// and note pElement1 is TYPE*, not TYPE
template<class TYPE, class ARG_TYPE>
BOOL AFXAPI CompareElements(const TYPE* pElement1,
                            const ARG_TYPE* pElement2)
           sizeof(TYPE), FALSE));
           sizeof(ARG_TYPE), FALSE));
    // for CMap<CString, LPCTSTR...>
    // we are comparing CString == LPCTSTR
    return *pElement1 == *pElement2;

Therefore, if you want to use CMap with your own custom ClassX, you will have to provide a specialized implementation for HashKey() and CompareElements().

Example: CMap with CString*

Provided as an example, below is what you need to do to make CMap work with CString*, and of course, using the string content as the key, and not the address of the pointer.

Hide Copy Code

UINT AFXAPI HashKey<CString*> (CString* key)
    return (NULL == key) ? 0 : HashKey((LPCTSTR)(*key));
// I don't know why, but CompareElements can't work with CString*
// have to define this
typedef CString* LPCString;
BOOL AFXAPI CompareElements<LPCString, LPCString>
     (const LPCString* pElement1, const LPCString* pElement2)
    if ( *pElement1 == *pElement2 ) {
        // true even if pE1==pE2==NULL
        return true;
    } else if ( NULL != *pElement1 && NULL != *pElement2 ) {
        // both are not NULL
        return **pElement1 == **pElement2;
    } else {
        // either one is NULL
        return false;

And the main program is as simple as:

Hide Copy Code

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
    CMap<CString*, CString*, int, int> map;
    CString name1 = "Microsoft";
    CString name2 = "Microsoft";
    map[&name1] = 100;
    int x = map[&name2];
    printf("%s = %d\n", (LPCTSTR)name1, x);*/
    return 0;

Hide Copy Code

--------- console output ---------
Microsoft = 100

Please note that the program can compile without error even without the specialized HashKey() and CompareElements(), but of course, the output will then be 0, probably not what you want.

My final note about CMap

  1. CMap is a hash map and STL::map is a tree map, there is no meaning comparing the two for performance (it would be like comparing apples and oranges!). But if you will retrieve the keys in sorted order, then you will have to use STL::map.
  2. The design of HashKey() is critical to the overall performance. You should provide a HashKey() that has a low collision rate (different keys generally would have different hash values) and is easy to calculate (not a MD5 of the string, etc..). And we have to note that — at least for some of the classes — this is not easy.
  3. When using CMap (as well as STL::hash_map), always beware of the hash table size. As quoted in MSDN, “the hash table size should be a prime number. To minimize collisions, the size should be roughly 20 percent larger than the largest anticipated data set”. By default, CMap hash table size is 17, which should be okay for around 10 keys. You can change the hash table size with InitHashTable(UINT nHashSize), and can only do so before the first element is added to the map. You can find more prime numbers here. (And don’t mix-up with CMap(UINT nBlockSize), nBlockSize is to acquire more than one CAssoc to speed up the creation of a new node.)

“CMAP 관련자료”의 26개의 댓글

  1. Hello! I’ve been reading your weblog for some time now and finally
    got the bravery to go ahead and give you a shout out
    from Atascocita Tx! Just wanted to mention keep up the good

  2. My programmer is trying to convince me to move to .net from PHP.
    I have always disliked the idea because of the costs.
    But he’s tryiong none the less. I’ve been using WordPress on a number of websites for
    about a year and am nervous about switching to
    another platform. I have heard excellent things about
    Is there a way I can transfer all my wordpress posts into
    it? Any kind of help would be really appreciated!

  3. I’m amazed, I must say. Rarely do I come across a blog that’s
    both equally educative and interesting, and let me tell you, you have
    hit the nail on the head. The problem is an issue that too few people are speaking intelligently about.
    I am very happy I came across this in my hunt for something concerning this.

  4. Pretty section of content. I just stumbled upon your weblog and in accession capital to assert that
    I get actually enjoyed account your blog posts. Anyway I’ll be subscribing to your augment and
    even I achievement you access consistently quickly.

  5. I just want to tell you that I’m very new to blogs and truly liked this blog. More than likely I’m likely to bookmark your blog . You amazingly come with outstanding stories. Thank you for sharing your webpage.

  6. Simply want to say your article is as surprising.

    The clarity in your post is just nice and i can assume you are
    an expert on this subject. Well with your permission let
    me to grab your feed to keep up to date with forthcoming post.
    Thanks a million and please carry on the enjoyable work.

  7. 핑백: fake glo carts

  8. 핑백: view our profile now

  9. 핑백: mơ thấy ác mộng

  10. 핑백: panzer bp12

  11. 핑백: olej konopny

  12. 핑백: cách nhớ bài catte

  13. 핑백: Skrota bilen

  14. 핑백: Skrotning av bil Uddevalla

  15. 핑백: Betalt for skrotbilar Kungälv

  16. 핑백: bốc mộ là gì

  17. 핑백: Buy Steroids Online

  18. 핑백:

  19. 핑백:

  20. 핑백: top replica watches

  21. 핑백: garage door repair nepean

  22. 핑백: Adderall for sale

댓글 남기기