CMap如何key为字符串,值为int
操作系统:WinXP
开发环境:VS2002 VS2005
CMap<CString, LPCTSTR, int, int>& mapPageNo 会报错,大意是没有哈希函数。VC的第版本只实现了3个函数函数,以此为基础加一个CString的函数就可以了。
通用的方法是定义成CMap<CString, LPCTSTR, int, int>:


也可自定义哈希函数。
#if _MSC_VER >= 1100
template<> UINT AFXAPI HashKey<CString> (CString key)
{
    return HashKey((LPCTSTR)key);
}
#else // _MSC_VER >= 1100
UINT AFXAPI HashKey(CString key)
{
    return HashKey((LPCTSTR)key);
}
#endif

void Ctest3Dlg::OnBnClickedButton1()
{
    CMap<CString,CString,int,int> a;
    a["dc"] = 3;
    int x = a["dc"];
}

 

=================

Win7+VC6

 

 char s1[] = "a";
 char s2[] = "a";
 CMap<const char*,const char*,int,int> m;
  m[s1]++;
 m[s2]++;

结果 m有两个元素

改成

CMap<CString,const char*,int,int> m;

就对了。

原因,默认情况下:

获取hash(哈希)实现了const char*,没实现CString, ==实现了CString,没实现const char*

posted on 2020-08-22 23:57  闻缺陷则喜何志丹  阅读(7)  评论(0编辑  收藏  举报  来源