Introduction
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:
- You are using primitive date types like
int
,char
, where pass-by-value makes no difference (may be even faster) with pass-by-reference. - If you use
CString
asKEY
, you should useLPCTSTR
asARG_KEY
and notCString&
, 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> AFX_INLINE UINT AFXAPI HashKey(ARG_KEY 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) #else UINT AFXAPI HashKey(LPCWSTR key) #endif { 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) #else UINT AFXAPI HashKey(LPCSTR key) #endif { 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, // TYPE=KEY, ARG_TYPE=ARG_TYPE // and note pElement1 is TYPE*, not TYPE template<class TYPE, class ARG_TYPE> BOOL AFXAPI CompareElements(const TYPE* pElement1, const ARG_TYPE* pElement2) { ASSERT(AfxIsValidAddress(pElement1, sizeof(TYPE), FALSE)); ASSERT(AfxIsValidAddress(pElement2, 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
template<> 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; template<> 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
CMap
is a hash map andSTL::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 useSTL::map
.- The design of
HashKey()
is critical to the overall performance. You should provide aHashKey()
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. - When using
CMap
(as well asSTL::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 withInitHashTable(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 withCMap(UINT nBlockSize)
,nBlockSize
is to acquire more than oneCAssoc
to speed up the creation of a new node.)
g into
g many
g https://tinyurl.com/rsacwgxy
http://t.co/4kPhN7Ek0L
tinyurl.com
cbd oil that works 2020
Davis Pillion
web hosting company
best web hosting sites
win money playing poker
Pingback: fake glo carts
Pingback: view our profile now
Pingback: mơ thấy ác mộng
Pingback: panzer bp12
Pingback: olej konopny
Pingback: cách nhớ bài catte
Pingback: Skrota bilen
Pingback: Skrotning av bil Uddevalla
Pingback: Betalt for skrotbilar Kungälv
Pingback: bốc mộ là gì
Pingback: Buy Steroids Online
Pingback: https://forex-fx.org/
Pingback: bollywood-slots.info
Pingback: top replica watches
Pingback: garage door repair nepean
Pingback: Adderall for sale
Pingback: rescator dumps
Pingback: Live Porn
Pingback: cvv fullz forum
Pingback: real-gomovies
Pingback: zügelfirma zürich
FN 503 9mm pistol
Pingback: ดูอนิเมะตอนเดียวจบ
Pingback: poker online
Pingback: garage door repair etobicoke
Pingback: tai w88
Pingback: http://fks-team.net/registracziya/
Pingback: mơ thấy mua nhà
Pingback: marketmenow
Pingback: Mail Bomber
Pingback: youtube live stream views buy
Pingback: garage door moving slow
Pingback: mơ thấy con sâu
tinder site
cheap flights
cheap flights
tinyurl.com
cheap flights
tinyurl.com
http://tinyurl.com/y5dknswb
http://tinyurl.com/yjpl3925
http://tinyurl.com/ydl7gckr
ps4 games
http://tinyurl.com
web hosting
tinyurl.com
minecraft games
0mniartist
gamefly off
asmr it
asmr was
of asmr
gamefly an
in asmr
tinyurl.com
asmr your
and asmr
http://j.mp/3uPrETE
tinyurl.com
tinyurl.com
https://785days.tumblr.com/
asmr an
dating sites of
with dating sites
in free dating sites
surgery scoliosis of
is surgery scoliosis
dating sites or
and free dating sites
tinyurl.com
http://tinyurl.com/y4ubqy5f
tadalafil online
what is tadalafil
tadalafil generic
tadalafil 40 mg from india
tadalafil max dose
best cbd gummies for sleep
seks homo
harga play spotify
buy weed online
SF Examiner
buy weed
buy tiktok followers
buy weed online
cbd gummies
buy tiktok followers
tiktok followers
buy weed online
weed near me
vibrating bullet massager
sex toy review
bullet vibe
most bizarre sex toys
prizebondlucky
Robert Mackay kai asset management
Carl Scholz
jasa view youtube live
Check This Out
Metal Injection Molding China
Video Marketing Experts
home
Seterus Short Sales
Camper Van Fiberglass Repair
Dentitox Pro Drops
Check This Out
ufabet
เว็บตรง pg
firayalal public school ranchi
worst Nile Cruise experience
Retirement Income
Wealth Advisor
rechargeable vibrator
Adam and Eve Coupon
North American Bancard Agent Program
사설토토사이트
fab filter mb
Дымоходы
Luxury Range Rover
Top Snapchat Women
Share Snapchat Name
penis pump review
thrusting vibrator
meticore complaints
the best sex toys for men
view website
emergency electrician
important source
Letha Terrey
get redirected here
Violet Freie
CBD oil UK
Maple Wollam
lost ways pdf
Davidlix
www xnalgas
best CBD oil UK
Michaelbup
Pinup
Charmaine
Jesse Grillo
Portsmouth water damage
remote vibrator tumblr
mens masturbator
tips on selling merchant services
To get your ex permanently
Daftar Situs Slot Pragmatic Play Terpercaya
wwwxnalgas
CMD368
Delphine
Ufabet
Zula Radosevich
Pilar Iverson
Emilia Nunziato
Missy Tostanoski
adult sex toy
Dorothea Sausedo
Melodi Hartory
Jane Safford
Evelia Ritell
Florence Mcnamer
Britney Kells
Jen Prevatt
Lakeshia Chorley
Minh Petterson
Karey Austell
sex toys for couples
Elly Avans
Neta Figart
Billye Spiry
g spot curved vibrator
Classie Ashwood
Daniell Gagel
Venessa Sempertegui
Janina Pacer
Leann Paray
best male prostate massager
188bet
rechargeable vibrator
benefits of anal sex
remote vibrating panty
Roofing Tampa
xnalgas vid
Best Gaming Headsets
my roofer
Data SGP
Kai Rob
Mudslides
meticore weight loss reviews
useful link
Lore Parlett
best CBD oil brands UK
jolca
click here
jual like fb
click here
gambar telanjang
click here
click here
Difference between Light Reaction and Dark Reaction
Male Strippers
iso agent
CBD oils UK
male masturbator
clitoral stimulator
Stories
Career
scholarships
파워볼사이트
milf free film
you could try this out
Mp3 Download
merchant services agent program
credit card processing agent programs
ISO credit card processing
Situs Slot Online Terbaik 2021
Bandar Judi Casino Online Terpercaya
Wells Fargo ISO Program
tree care service near me
become a digital payment agent
http://tinyurl.com
best sex toys reviews
tinyurl.com
male sex toy
bokep
j.mp
bitly.com
moving company
bitly.com
Golf Club Shafts
Steroids
http://tinyurl.com
Local Shroom Delivery
http://tinyurl.com
Shrooms Vancouver
Magic Mushroom Vancouver
K2 visa
best vibrators for beginners
best clit sucker
merchant services agent
fun88
North American Bancard ISO
https://bibliocrunch.com/profile/cachlammonngonvn/
http://bitly.com/
gamefly it
best bullet vibrator
rechargeable bullet vibrators
Exotic Car Rental Miami
Exotic Car Rental Miami
Exotic Car Rental Miami
buy dumps with cvv
best fullz shop
the ps4 games
Top World Tours
adam and eve male sex toys
this ps4 games
pocket strokers
top stocks
stock investment
Data Extraction Services
stock market explained
tiktok takipçi satın al
dildo for beginners
remote control sex toys
bit.ly
manhwaland
scoliosis surgery what
their scoliosis surgery
loosymn
Propecia
สล็อตเว็บตรง
สล็อตเว็บตรง แตกง่าย
Speeddy
it quest bars
Stromectol
bitly.com
bitly.com
compilation
compilation
firma de transport
www.iherb.com
arşiv haberler
live adult webcam
http://coub.com/stories/962966-scoliosis-surgery
avengers endgame i·zle
Lasix
Marquerite Beswick
Norah Campolongo
Thanh Cleamons
pay day loans
oppossy
dildos for women
p spot massager
good online sex stores
penis vacuum pump
noi hoi
최상위파워볼
schmuck
best shopping streets. Stories
best smm panel
best dumps shop 2021
top pet care boulder
PaydayFum
smm panel instagram followers
genesis tree service reston
menengiç türk kahvesi
Pingback: Temp Mail
Seo for auto repair shops in phoenix
dolor de espalda mezclar diclofenac y neurontine
Best seo in arizona
elisa oliver chaturbate
สล็อตเปิดใหม่
สล็อตเว็บใหญ่
สล็อตแตกง่าย
Cishose
crearne
Fortnite
visit site
best hospital in ahmedabad
best hospital in ahmedabad
live sexy video chat
Send Money to Pakistan
Does phenq really work
Keynote Public Speaker
Best Travel Items
acrylic paint
situs judi slot online terpercaya 2021
SERRO29
HEALAN20
TRIPPET99
INOCENCIO40
Asa Purnell
URQUIJO74
stripchat indian
Billie Haar
hot video chat
Frederick Anneler
LAHEY21
KEBEDE51
HORNBECK46
HERZFELD75
ALFREDO44
Layla Goetzke
MUROS38
SIMMS56
ROSTEK13
GAYNE31
SCHOUTEN40
Armand Truslow
REOME10
why ps4 games
OSOSKIE38
Chris Rooker
MELBERT13
MENDRIN27
Terrence Abramian
Ina Dominique
Jenice Feris
Dinkdasia
HOBBINS09
Jerry Dravland
FORESTER95
WEISSBRODT25
ZATORSKI22
KABRICK64
Esteban Rosenbush
STEIN87
Marcus Bloodsworth
difference between viagra and levitra
SKENE48
Barney Kittredge
holorma
prednisone over counter in costa rica
is asmr
erdal can alkoçlar
child porn
porn video
Erdal can alkoçlar
bagimsizgazete.com
Lilla Pattengale
asmr or
Rolando Narkevicius
Logan Damerell
eskişehir çilingir orhangazi
Kurumsal boyacı
Felipe Momplaisir
Adalberto Shewmaker
Ty Heam
Elfreda Phelp
off asmr
Tracie Marius
Tori Dobkin
Pamila Hugus
Trent Balthazar
Casie Estep
Amal Yankovich
Beatrice Avallone
Rema Lemley
Alease Breu
Avşa otel
Jonathan Speyrer
Donna Dellen
Santina Crimes
sex fuck
Ruben Nobriga
נערות ליווי בחיפה
Stevie Mottram
Artificial grass belfast
Beaulah Honga
Lucas Moncur
Martha Stiehl
Dewey Blacknall
Coleman Alsbury
advertorialreklam.com
Cammy Her
Dulcie Betty
Floocop
RV Upholstery Repair Near Me
Devora Depalma
Nell Nakken
Nathalie Hubley
Douglas Derose
Dominique Lipham
Teresita Mincher
browning 1911 compact 380
happy whell
happy wings
beretta tomcat
Fiberglass RV Repair Near Me
trump is your daddy
trump 2024
happy burger
happy pokemon
Best RV Technician Around My Neighborhood
happy anime
happy happy
Best RV Body Work Around Me
watch high HD videos
Best RV Repair Shops By My Spot
Best RV Shops By My Area
Buy Percocet online
Travel Trailer Parts Near Me
Motorhome Repair Company Near Me
Rv Body Shops Near Me
Motor Home Repair Near Me
Rv Maintenance Near Me
Darren Joganic
Sprinter Boxwoods Near Me
Mercedes Sprinter Maintenance Service Near Me
Bernarda Vanord
Motorhome Awnings Supplied And Fitted Near Me
Digital Marketing Services For Small Business
ซุปเปอร์ สล็อต เครดิตฟรี
Aurelio Leuga
Start A Digital Marketing Agency
Internet Marketing Companies
Mercedes Sprinter Maintenance Service Near Me
Rv And Camper Repair Near Me
taurus tx22 for sale
Willy Puca
Online Advertising Business
Small Toy Hauler Camper Near Me
Lakia Gelzinis
Pablo Botha
Social Media Marketing Service
Banners Company Near Me
Ford Motorhome Repair Near Me
Mercedes Sprinter Van Repair Shops Near Me
Leo Shade
Huong Kai
Cassy Fahrenwald
Floy Merrick
Abdul Ackley
burn injury lawyer near me
Porfirio Wadden
Website Services Near Me
Woodrow Goolia
Keith Loiselle
Aubrey Schimming
Cornelius Gelles
RV Repair Seal Beach
Mobile Motorhome Repairs Near Me
RV Awning Orange County
ליווי בחיפה
נערות ליווי בנשר
Boat Trailer Supplies Near Me
Boris Manny
Miles Conser
Food Trailer Manufacturers Near Me
Sprinter Brake Switch Near Me
Camper Expo Near Me
Rv Purchase Near Me
RV Cabinet California
Camper Cabins Near Me
Rene Marbus
Cira Balhorn
Nguyet Cypret
Cole Yancik
Toy Hauler Trailers Near Me
RV Refrigerator Orange County
RV Windows Near Me
Motorhome Pitches Near Me
Roselle Duresky
Wilda Zoumis
Lucien Froozy
Vernice Tio
Motorhome Awnings Supplied And Fitted Near Me
trump won
the number 1 dumb fuck
childish adult
emotionally unstable moron
barandergisi.net
definition of loser
childish adult
Penni Steinour
Damien Farlow
Garret Williar
Damien Weatherbee
Sasha Leuters
Jamaal Krzemien
Cedrick Sweely
Willa Tatis
Irving Litwin
Carissa Sayavong
Ardath Cooperstein
Lamont Swartzman
Jose Fike
Janessa Whatcott
jetsZers
Darell Nuckles
Body Shops Places Around Me
Sprinter Van Size Chart
Valorie Kearn
Nicky Navarra
Luxury Sprinter Van
Body Shops Near My Shop
Facebook Ads Certification
Pedro Nilles
Sprinter Van Seat Covers
Lamont Kaloustian
Dani Schell
Chevy Camper Van Interior
Jamey Bater
Donny Pollett
Torie Rosseter
geveze sohbet
Lionel Tumolo
Shanel Cansino
Nickolas Garbarini
shurry
Vw Van For Sale Near Me
Courtney Majka
Glory Zbell
Dung Beltz
Forrest Rast
Genny Ulatowski
Selina Dobrin
Sol Denard
Mariana Fasci
Fence Installer Jobs Near Me
Darell Nosbisch
Marcelo Kraska
whatsapp indir
Chery Iuliano
personal professional development planning
zastava m70
Website Arrow Gif
Ike Korbar
Karmen Borkowski
how did gina on b positive get rich
f2 savannah kittens for sale
Robbie Cluster
Hellen Cubano
simple flower engraving designs
Forklifts Near Me
signet ring engraving near me
Jules Caira
Taylor Forklift Near Me
Kris Bredehoft
Jennifer Harrist
Case Lift Trucks
Whats A Grease Trap
Carlyn Ulloa
Travel Trailer Supplies Near Me
Mercedes Benz Sprinter Rv Near Me
Frederic Mayotte
Darrel Boardwine
Camper Van Parts
Custom Sprinter Van With Bathroom
Mercedes Sprinter Mechanic Near Me
Sprinter Van For Sale Under $5 000
Rv Plumbing Repair Near Me
Chantay Sottile
Halay
Lory Cipcic
Motorhome Repair Reviews Near Me
springfield 911 for sale
century arms
Halay
Jarrod Memmo
youtube mp3 indir
Hedy Stanchfield
Rafael Teles
RV Window Shades Oc California
DIY Over The Cab Drop Down Beds For Van
Benchmark Vehicles Conversion Near Me
International Hx Orange County
Keystone Travel Trailer Near Me
Camper Disposal Near Me
RV Collision Maintenance Services
RV Remodeling Services
RV Windshields Orange County
MARQ® Driver
Camper Floor Repair Near Me
RV Repair Orange County
Pingback: Netflix bez VPN
Pingback: online moskva psiholog
Pingback: psy online
Pingback: uels ukrain
Pingback: Psychologists