简体   繁体   English

当大小为零时,hash_map在第一次查找期间崩溃

[英]hash_map crashing during the first find when size is zero

I am new to hash_map in c++. 我是C ++中的hash_map的新手。 I have to convert a table in to hashmap. 我必须将表转换为哈希表。

This is how I have declared and using hash_map in my program 这就是我在程序中声明和使用hash_map的方式

I am using microsoft visual studio. 我正在使用Microsoft Visual Studio。

#include <hash_map>
using namespace stdext;
typedef hash_multimap <const char*, long > HEAPTABLE;

typedef HEAPTABLE::iterator HEAP_ITER;

class CTest
{

public:

 void setSwitchID(long i);
 long getSwitchID();
 void isUpgrading(bool bTest);
private:

 HEAPTABLE m_hashMap;
};

void CTest::setSwitchID(long dwID)
{


 HEAP_ITER hIter = m_hashMap.find("SwitchId");
 if (hIter != m_hashMap.end())
 {
  hIter->second = dwID;
 }
 else
 {
  m_hashMap.insert(make_pair("SwitchId", dwID));
 }

}

long CTest::getSwitchID()
{

 HEAP_ITER hIter = m_hashMap.find("SwitchId");
 if (hIter != m_hashMap.end())
 {
  return hIter->second;
 }
 return 0;

}

int _tmain(int argc, _TCHAR* argv[])
{

  CTest* test = new CTest;
          if (test)
          {

  test->setSwitchID((DWORD)i);
  test->isUpgrading(false);
         }
 delete test;
 return 0;

}

This code works fine when I run it as a separate program but when I try run it as part of my project the application crashes. 当我将其作为单独的程序运行时,此代码运行良好,但是当我尝试将其作为项目的一部分运行时,应用程序崩溃。 Even if there are no entry in the map the hIter in the set function is returning bad pointer. 即使映射中没有条目,set函数中的hIter也会返回错误的指针。 Is this because of memeory corruption? 这是因为内存损坏吗? Could you please help? 能否请你帮忙?

If it is a heap corruption, how can i avoid this? 如果是堆损坏,如何避免这种情况? Is there anyway I can say create a hash_map with this size? 无论如何,我可以说创建具有此大小的hash_map吗?

hash_multimap <const char*, long > does not do what you think it does. hash_multimap <const char*, long >不会执行您认为的操作。 The key is a pointer not a string. 关键是指针而不是字符串。 Your small program works by luck of compiler using the same memory for both "SwitchId" string literals. 您的小程序会靠运气好的编译器为两个"SwitchId"字符串文字使用相同的内存。 This is not the case in a larger project. 在较大的项目中情况并非如此。

Use std::string as a key instead and, while here, switch to std::unordered_multimap . 请使用std::string作为键,并在此处切换到std::unordered_multimap

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM