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.)

Comments (297)

  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. Pingback: fake glo carts

  8. Pingback: view our profile now

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

  10. Pingback: panzer bp12

  11. Pingback: olej konopny

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

  13. Pingback: Skrota bilen

  14. Pingback: Skrotning av bil Uddevalla

  15. Pingback: Betalt for skrotbilar Kungälv

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

  17. Pingback: Buy Steroids Online

  18. Pingback:

  19. Pingback:

  20. Pingback: top replica watches

  21. Pingback: garage door repair nepean

  22. Pingback: Adderall for sale

  23. Pingback: rescator dumps

  24. Pingback: Live Porn

  25. Pingback: cvv fullz forum

  26. Pingback: real-gomovies

  27. Pingback: zügelfirma zürich

  28. 응답

    Thankѕ for another informative website. Where else may I get that type of information written in such an ideal means? Ӏ have a miѕsion that I’m just now working on, and I’ve been at the glance out for such info.

  29. Pingback: ดูอนิเมะตอนเดียวจบ

  30. Pingback: poker online

  31. Pingback: garage door repair etobicoke

  32. Pingback: tai w88

  33. Pingback:

  34. Pingback: mơ thấy mua nhà

  35. Pingback: marketmenow

  36. Pingback: Mail Bomber

  37. Pingback: youtube live stream views buy

  38. Pingback: garage door moving slow

  39. Pingback: mơ thấy con sâu

  40. 응답

    It’s very straightforward to find out any topic on web as compared to books, as I found this
    piece of writing at this web page.

  41. 응답

    magnificent issues altogether, you just received a logo new
    reader. What would you suggest in regards to your post that you simply made a few days in the past?

    Any sure?

  42. 응답

    I was suggested this web site by my cousin. I am not sure
    whether this post is written by him as no one else know such detailed about
    my difficulty. You’re wonderful! Thanks!

  43. 응답

    Magnificent goods from you, man. I have take into accout your stuff prior to and you are simply too wonderful.
    I really like what you’ve received here, certainly like what you’re saying and the best way through which you
    are saying it. You’re making it enjoyable and you still care for to keep it wise.
    I can not wait to learn much more from you. That is actually a tremendous site.

  44. 응답

    I’d like to thank you for the efforts you’ve put in penning this blog.
    I am hoping to check out the same high-grade content from you later
    on as well. In truth, your creative writing abilities has motivated me to get my very own website now 😉 ps4 games allenferguson ps4 games

  45. 응답

    whoah this weblog is wonderful i really like reading your articles.
    Keep up the great work! You recognize, a lot of individuals are searching round for this info, you could help
    them greatly.

  46. 응답

    Simply want to say your article is as astonishing.
    The clarity in your post is simply nice and i could assume you’re
    an expert on this subject. Fine with your permission allow me to grab your feed to keep up to date with forthcoming post.
    Thanks a million and please keep up the gratifying work.

  47. 응답

    A fascinating discussion is worth comment. I believe that you should write
    more on this subject matter, it may not be a taboo subject but typically folks don’t
    discuss these issues. To the next! Many thanks!!

  48. 응답

    I do trust all the concepts you’ve introduced on your post.
    They are really convincing and will definitely work. Nonetheless, the
    posts are too quick for beginners. May just you please lengthen them a bit from next time?
    Thank you for the post. asmr 0mniartist

  49. 응답

    I do not even know how I ended up here, but I thought this post was good.
    I don’t know who you are but certainly you’re
    going to a famous blogger if you are not already 😉 Cheers!

  50. 응답

    Somebody essentially assist to make critically posts I’d state.
    This is the first time I frequented your web page and to this point?
    I amazed with the analysis you made to make this actual publish extraordinary.
    Wonderful activity!

  51. 응답

    Hi, I do think this is a great web site. I stumbledupon it 😉
    I’m going to return yet again since i have book marked
    it. Money and freedom is the best way to change, may you be rich and continue to guide others.

  52. 응답

    These are really impressive ideas in regarding blogging.
    You have touched some nice things here. Any way keep up wrinting.

  53. 응답

    Greate post. Keep writing such kind of info on your site. Im really impressed by
    your site.
    Hello there, You have performed an excellent job. I will certainly digg
    it and in my view recommend to my friends. I’m confident they will be benefited from this site.

  54. 응답

    Heya i am for the primary time here. I came across
    this board and I to find It truly helpful & it helped me out much.
    I am hoping to give something back and aid others such as you helped me.

  55. 응답

    I blog often and I genuinely appreciate your content.

    Your article has truly peaked my interest. I am going
    to bookmark your website and keep checking for new details about once a week.
    I subscribed to your RSS feed as well.

  56. 응답

    Heya i’m for the primary time here. I came across this board and I in finding It
    truly helpful & it helped me out a lot. I’m hoping to present something again and help others
    such as you helped me.

  57. 응답

    It is in point of fact a great and helpful piece of info. I am satisfied that you shared this helpful information with us.
    Please stay us up to date like this. Thank you for sharing.


  58. 응답

    I love your blog.. very nice colors & theme. Did you create this website
    yourself or did you hire someone to do it for you? Plz answer back
    as I’m looking to create my own blog and would
    like to find out where u got this from. many thanks scoliosis

  59. 응답

    Hi there! Would you mind if I share your blog with my facebook group?
    There’s a lot of folks that I think would really enjoy your content.
    Please let me know. Many thanks scoliosis

  60. 응답

    Normally I don’t read article on blogs, however I wish to say that this write-up very compelled me to try and do so!
    Your writing style has been surprised me. Thanks, quite great post.

  61. 응답

    I was more than happy to uncover this page.
    I want to to thank you for ones time for this wonderful read!!
    I definitely savored every bit of it and i also have you saved as a favorite to look at new things
    in your website.

  62. 응답

    Hi, i believe that i saw you visited my blog thus i came to return the favor?.I’m trying to
    in finding things to improve my website!I assume
    its ok to use some of your concepts!!

  63. 응답

    Thanks , I have just been looking for information about this topic for a while
    and yours is the best I’ve found out till now. But, what in regards to the bottom line?

    Are you certain about the supply?

  64. 응답

    Oh my goodness! Amazing article dude! Thank you, However
    I am experiencing issues with your RSS. I don’t understand why I can’t subscribe to
    it. Is there anybody having the same RSS issues?

    Anyone that knows the answer can you kindly respond? Thanks!!

  65. 응답

    Undeniably believe that that you stated. Your favourite justification appeared to
    be on the net the simplest factor to take into account of.
    I say to you, I certainly get irked even as other people consider issues that they just don’t
    recognize about. You managed to hit the nail upon the highest and
    also outlined out the whole thing with no need side-effects ,
    folks could take a signal. Will likely be back
    to get more. Thanks

  66. 응답

    I was recommended this web site by my cousin. I’m not sure whether this post is written by him as nobody else know such detailed about my difficulty.
    You’re incredible! Thanks!

  67. 응답

    [url=]дымоходы из нержавейки[/url]

    Предлагаемый нами дымоход используется чтобы отвода выхлопных газов прямо из печи, камина сиречь козла внутри помещения. Использование такой трубы позволяет делать привлекательные архитектурные решения и в то же эпоха более эффективно извлекать тепло выхлопных газов.

    Стальной дымоход изготовлен из двухмиллиметрового стального листа. Эти качественные трубы каминной печи дополнительно покрыты лаком Senotherm толщиной 2 мм. Лак делает дымоход устойчивым к высоким температурам – до 600 градусов.
    дымоходы из нержавейки

  68. 응답
  69. 응답

    pin-up casino онлайн
    pin up casino зеркало
    казино пин ап

    [url=]pin up casino[/url]
    [url=]pin up casino[/url]
    [url=]pin up casino[/url]
    [url=]pin up casino[/url]
    [url=]pin up casino[/url]
    [url=]pin up casino[/url]
    [url=]pin up casino[/url]
    [url=]pin up casino[/url]
    [url=]pin up casino[/url]
    [url=]pin up casino[/url]
    [url=]pin up casino[/url]
    [url=]pin up casino[/url]
    [url=]pin up casino[/url]
    [url=]pin up casino[/url]
    [url=]pin up casino[/url]
    [url=]pin up casino[/url]
    [url=]pin up casino[/url]
    [url=]pin up casino[/url]
    [url=]pin up casino[/url]
    [url=]pin up casino[/url]

    pin up casino

    pin up casino
    pin up casino
    pin up casino
    pin up casino
    pin up casino
    pin up casino
    pin up casino
    pin up casino
    pin up casino
    pin up casino
    pin up casino
    pin up casino
    pin up casino
    pin up casino
    pin up casino
    pin up casino
    pin up casino
    pin up casino
    pin up casino
    pin up casino

  70. 응답

    [url=]pin up казино[/url]

    Наши специалисты неослабно следят ради рынком tie tack up casino, предоставляя нашим читателям самые свежие акции и привлекательные предложения. Мы тратим громада времени для тестирование казино, чтобы убедиться, сколько мы рекомендуем только лучшие!

    Вдруг встречать самые надежныепин ап казинос широчайшим выбором игр, которые также предлагают фантастические акции и предложения? Вы можете найти противоречие для сей вопрос здесь.
    pin up казино

  71. 응답

    That is really attention-grabbing, You are an overly professional
    blogger. I have joined your feed and look ahead to in search of more
    of your fantastic post. Additionally, I’ve shared your site in my social networks

  72. 응답

    Hello! I could have sworn I’ve been to this web site
    before but after browsing through many of the articles I realized it’s new to me.
    Anyhow, I’m definitely pleased I discovered it
    and I’ll be book-marking it and checking back regularly!

  73. 응답

    each time i used to read smaller articles or reviews that also clear
    their motive, and that is also happening with this
    post which I am reading at this time.

  74. 응답

    Have you ever thought about including a little bit more
    than just your articles? I mean, what you say is important
    and all. But just imagine if you added some great graphics
    or videos to give your posts more, “pop”! Your content
    is excellent but with images and videos, this blog could certainly be one of
    the most beneficial in its field. Fantastic blog!

  75. 응답

    Someone essentially assist to make critically posts I might state.
    This is the first time I frequented your website page and to this point?
    I surprised with the research you made to create this
    particular post incredible. Magnificent activity!

  76. 응답

    What i don’t understood is in reality how you are no longer really much more smartly-liked than you might be now.
    You are so intelligent. You realize thus significantly
    in relation to this matter, made me in my opinion believe it from numerous various angles.
    Its like men and women are not involved unless it is something
    to accomplish with Girl gaga! Your personal stuffs nice.

    All the time maintain it up!

  77. 응답

    I am really impressed with your writing skills as smartly as
    with the structure in your blog. Is that this a paid subject matter or did you modify it your self?
    Either way stay up the excellent quality writing, it’s rare to see a
    nice weblog like this one nowadays..

  78. 응답

    Someone essentially assist to make severely posts
    I might state. This is the first time I frequented your web
    page and to this point? I surprised with the research you made to
    create this particular put up amazing. Excellent job!

  79. 응답

    Howdy would you mind sharing which blog platform you’re using?

    I’m looking to start my own blog soon but I’m having a hard time selecting between BlogEngine/Wordpress/B2evolution and Drupal.

    The reason I ask is because your design seems different
    then most blogs and I’m looking for something completely unique.
    P.S My apologies for being off-topic but I had
    to ask!

  80. 응답

    Today, I went to the beach front with my children. I found a sea
    shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed the shell to her ear and screamed.
    There was a hermit crab inside and it pinched her ear.
    She never wants to go back! LoL I know this is totally off topic but
    I had to tell someone!

Leave a comment

이메일 주소는 공개되지 않습니다.