CMap在用CString做key类型时,ARG_KEY要选LPCTSTR

2024-04-03 07:18

本文主要是介绍CMap在用CString做key类型时,ARG_KEY要选LPCTSTR,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

CMap在用CString做key类型时,ARG_KEY要选LPCTSTR 
文章来源:http://blog.csdn.net/flyingxu/archive/2005/12/26/562852.aspx

遇到好几个人说CMap在用CString做key类型时有问题,说用int和DWORD就可以,用CString就不行。因此很多人推荐使用MFC中的CMapStringToPtr之类。

看下面的代码:
//.h
    CMap<CString, LPCTSTR, int, int> typeMap;
//.cpp
    typeMap.SetAt(_T("ONE"),1);
    typeMap.SetAt(_T("TWO"),2);

    int nValue = 0;
    BOOL ret = typeMap.Lookup(_T("ONE"), nValue);
    ret = typeMap.Lookup(_T("THREE"), nValue);
    ret = typeMap.Lookup(_T("TWO"), nValue);
我的代码运行的很好,我觉得关键是ARG_KEY要选LPCTSTR

原因:  referencehttp://www.codeproject.com/KB/architecture/cmap_howto.aspx

Introduction

Programmers like me, who learnt STL::map before CMap, always think CMap is difficult to use, and always try to useCMap 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 withCString* (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) asSTL::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 justCMap<KEY, VALUE>?

In fact, the ultimate data container in CMap is CPair, and the internal of CPair is {KEY, VALUE}. Therefore, CMapwill 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_KEYseems always a correct thing, except when:

  1. You are using primitive date types like intchar, 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:

// 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 norCStringW, 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.

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

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:

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;
}
--------- console output ---------
Microsoft = 100

Please note that the program can compile without error even without the specialized HashKey() andCompareElements(), 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在用CString做key类型时,ARG_KEY要选LPCTSTR的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/872251

相关文章

IDEA如何将String类型转json格式

《IDEA如何将String类型转json格式》在Java中,字符串字面量中的转义字符会被自动转换,但通过网络获取的字符串可能不会自动转换,为了解决IDEA无法识别JSON字符串的问题,可以在本地对字... 目录问题描述问题原因解决方案总结问题描述最近做项目需要使用Ai生成json,可生成String类型

深入理解Redis大key的危害及解决方案

《深入理解Redis大key的危害及解决方案》本文主要介绍了深入理解Redis大key的危害及解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着... 目录一、背景二、什么是大key三、大key评价标准四、大key 产生的原因与场景五、大key影响与危

python 字典d[k]中key不存在的解决方案

《python字典d[k]中key不存在的解决方案》本文主要介绍了在Python中处理字典键不存在时获取默认值的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录defaultdict:处理找不到的键的一个选择特殊方法__missing__有时候为了方便起见,

Mysql 中的多表连接和连接类型详解

《Mysql中的多表连接和连接类型详解》这篇文章详细介绍了MySQL中的多表连接及其各种类型,包括内连接、左连接、右连接、全外连接、自连接和交叉连接,通过这些连接方式,可以将分散在不同表中的相关数据... 目录什么是多表连接?1. 内连接(INNER JOIN)2. 左连接(LEFT JOIN 或 LEFT

Redis的Hash类型及相关命令小结

《Redis的Hash类型及相关命令小结》edisHash是一种数据结构,用于存储字段和值的映射关系,本文就来介绍一下Redis的Hash类型及相关命令小结,具有一定的参考价值,感兴趣的可以了解一下... 目录HSETHGETHEXISTSHDELHKEYSHVALSHGETALLHMGETHLENHSET

Python中异常类型ValueError使用方法与场景

《Python中异常类型ValueError使用方法与场景》:本文主要介绍Python中的ValueError异常类型,它在处理不合适的值时抛出,并提供如何有效使用ValueError的建议,文中... 目录前言什么是 ValueError?什么时候会用到 ValueError?场景 1: 转换数据类型场景

C# dynamic类型使用详解

《C#dynamic类型使用详解》C#中的dynamic类型允许在运行时确定对象的类型和成员,跳过编译时类型检查,适用于处理未知类型的对象或与动态语言互操作,dynamic支持动态成员解析、添加和删... 目录简介dynamic 的定义dynamic 的使用动态类型赋值访问成员动态方法调用dynamic 的

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]

自定义类型:结构体(续)

目录 一. 结构体的内存对齐 1.1 为什么存在内存对齐? 1.2 修改默认对齐数 二. 结构体传参 三. 结构体实现位段 一. 结构体的内存对齐 在前面的文章里我们已经讲过一部分的内存对齐的知识,并举出了两个例子,我们再举出两个例子继续说明: struct S3{double a;int b;char c;};int mian(){printf("%zd\n",s

【编程底层思考】垃圾收集机制,GC算法,垃圾收集器类型概述

Java的垃圾收集(Garbage Collection,GC)机制是Java语言的一大特色,它负责自动管理内存的回收,释放不再使用的对象所占用的内存。以下是对Java垃圾收集机制的详细介绍: 一、垃圾收集机制概述: 对象存活判断:垃圾收集器定期检查堆内存中的对象,判断哪些对象是“垃圾”,即不再被任何引用链直接或间接引用的对象。内存回收:将判断为垃圾的对象占用的内存进行回收,以便重新使用。