码农(假) 2018-06-14 01:52 采纳率: 100%
浏览 950
已采纳

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

  • 写回答

5条回答 默认 最新

  • howenjoyce 2018-06-15 07:04
    关注

    之所以出现这个问题,是因为: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;
    }

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况