MFC中CMap的使用问题。
本想用 char 字符串做主键。
我定义了个类成员,类型: CMap《const char ※,const char ※,int,int》
在类内一个函数里 new 的 字符串 set 进去,在另外一个 函数里 拿一个字符串去查找 就找不到了。。。
难道要拿着那个 set 进去的指针去找么 ?
我不知道想 用char 数组做主键应该怎么定义,难道CMap不支持么?
class CMyClass
{
public:
CMyClass();
~CMyClass();
void Set(char * pname, int n);
int Get(char* pname);
CMap<const char*, const char*, int, int> m_mapTest;
};
void CMyClass::Set(char * pname,int n)
{
char* pName = new char[20]{ 0 };
strcpy_s(pName, 20, pname);
m_mapTest.SetAt(pName, n);
}
int CMyClass::Get(char* pname)
{
POSITION pos = m_mapTest.GetStartPosition();
const char* pKey=NULL;
while (pos)
{
int n = 0;
m_mapTest.GetNextAssoc(pos, pKey, n);
if (strcmp(pKey, pname) == 0)
break;
}
int n = 0;
if (m_mapTest.Lookup(pKey, n))
{// 这里 可以进来,如果要这样才能查找到对应的value 我还用 CMap 干嘛。。。
int x = n;
}
if (m_mapTest.Lookup(pname, n))
{// 这里进不来
int x = n;
}
return n;
}
之所以出现这个问题,是因为:CMap m_mapTest; 这样的写法表示Key的比较方式是按照地址的方式来查找,
即你set进去的地址是多少,找的key的地址就应该多少。
如果要以内容比较的方式(即const char* 指向的字符串),用楼上说的CString作为Key的定义去做。
以下的代码的ptest_key是同一地址,并且改了Set函数,直接将改地址存放作为Key,则可以找到的:
#include "stdafx.h"
#include
class CMyClass
{
public:
CMyClass() {}
~CMyClass() {}
void Set(char * pname, int n);
int Get(const char* pname);
CMap<const char*, const char*, int, int> m_mapTest;
};
void CMyClass::Set(char * pname, int n)
{
char* pName = new char[20]{ 0 };
strcpy_s(pName, 20, pname);
//m_mapTest.SetAt(pName, n);
m_mapTest.SetAt(pname, n);
}
int CMyClass::Get(const char* pname)
{
POSITION pos = m_mapTest.GetStartPosition();
const char* pKey = NULL;
while (pos)
{
int n = 0;
m_mapTest.GetNextAssoc(pos, pKey, n);
if (strcmp(pKey, pname) == 0)
break;
}
int n = 0;
if (m_mapTest.Lookup(pKey, n))
{// 这里 可以进来,如果要这样才能查找到对应的value 我还用 CMap 干嘛。。。
int x = n;
}
if (m_mapTest.Lookup(pname, n))
{// 这里进不来
int x = n;
}
return n;
}
int main()
{
char * ptest_key = "我是谁?";
CMyClass c;
c.Set(ptest_key, 1);
c.Get(ptest_key);
return 0;
}
先看看字符串是不是完全相等。CMap支持char*
https://blog.csdn.net/liujiayu2/article/details/46121219?locationNum=4&fps=1
能贴一下代码吗,你这个描述太笼统了,难试出来
可以这么创建,CMap ,我都是这么用的,亲测可用
可以这么创建, CMap《CString,LPCTSTR,int,int》,我都是这么用的