c++ - std::map::find(char*) 在 Debug模式下无法在 64 位机器上运行

标签 c++ windows

我面临一个有趣的情况,想与大家分享。当然,如果有人能提供帮助,我将不胜感激!

#include "stdafx.h"
#include <map>

#define DEF_NAME1   "NAME1" 
#define DEF_NAME2   "NAME2" 
#define DEF_NAME3   "NAME3" 
#define DEF_NAME4   "NAME4" 

struct TInfo
{
    const char * TName;
    const char * TArray1[100];
    const char * TArray2[100];
};

typedef std::map<const char*, TInfo*> TInfoMap;
typedef std::pair<const char*,TInfo*> TInfoPair;

static TInfoMap tinfomap;

TInfo TInfoArray[] =
{
{DEF_NAME1,{""}, {""}},
{DEF_NAME2,{""}, {""}},
{DEF_NAME3,{""}, {""}},
{DEF_NAME4,{""}, {""}}
};

TInfoMap* GetTInfoMap()
{

for (int i = 0; i < 3 ; i++ )
    tinfomap.insert(TInfoPair(TInfoArray[i].TName,&TInfoArray[i]));

return &tinfomap;
}


int _tmain(int argc, _TCHAR* argv[])
{
char *name="NAME3";

TInfo* ptr = new TInfo();

TInfoMap* map1 = GetTInfoMap(); 

if ( map1->find(name) == map1->end() )
    printf("Not found");
else
    printf("Found!");

return 0;
}

我在 windows 2003 Server 64 位上。我得到输出“找到!”当我在 Release模式下编译/运行此程序时,当我在 Debug模式下编译/运行此程序时输出为“未找到”。

有什么想法吗?

问候,

阿哲

最佳答案

尝试使用 std::string 作为映射中的键。 当您使用 char* 作为键时出现问题, map 比较 char* 的地址而不是您期望的内容。如果你想使用 char* 作为键,你需要使用比较谓词实例化映射作为模板的第三个参数。

这里调试和发布配置之间的区别可能解释了常量字符串文字是如何存储的——是相同的还是单独的存储用于相同的字符串

你并不孤单link

关于c++ - std::map::find(char*) 在 Debug模式下无法在 64 位机器上运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1232361/

相关文章:

c++ - 使用 BOOST::associative property map 插入 boost::BIMAP ... 失败

c++ - openCV imdecode 工作缓慢

windows - 如何将低级命令(非 APDU)发送到 Windows 10(移动)上的智能卡?

windows - Windows 中的 svn/ssh 问题

Windows 上的 Java : how to delete a file to trash (using JNA)

c++ - 获取 vector 中所有元素的某个组件

c++ - 使用 openMP 计算复 vector 的点积

c++ - 使用 clang API 打印参数的类型 (ParmVarDecl)

windows - GetModuleHandle() 是如何工作的?

C# Windows 服务 - 自动启动然后停止