1 回答

TA貢獻1856條經驗 獲得超11個贊
之所以出現這個問題,是因為: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;
}
- 1 回答
- 0 關注
- 1272 瀏覽
添加回答
舉報