亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

MFC中CMap的使用問題。

MFC中CMap的使用問題。

C++
慕娘9325324 2018-07-18 13:18:13
本想用 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; }
查看完整描述

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;
}


查看完整回答
反對 回復 2018-07-27
  • 1 回答
  • 0 關注
  • 1272 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號