带有char *键的C ++ unordered_map会产生意外行为

时间:2013-07-06 20:19:31

标签: c++ c++11 functor unordered-map arrays

我尝试使用unordered_map将char *键散列为整数值。在编写自定义仿函数以进行散列并比较char *之后,无序映射似乎正常工作。但是,我最终注意到哈希会偶尔返回不正确的结果。我创建了一个测试项目来重现错误。下面的代码创建一个带有char *键和自定义仿函数的unordered_map。然后它运行1000x周期并记录发生的任何哈希错误。我想知道我的仿函数是否有问题,或者问题是否存在于unordered_map中。任何帮助,将不胜感激。谢谢!

#include <cstdlib>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <tr1/unordered_map>

using namespace std;

//These varaibles are just used for printing the status.
static const char* c1;
static const char* c2;
static int cmpRet;
static int cmpVal;
static const char* hashChar;
static size_t hashVal;

// Character compare functor.
struct CmpChar {

  bool operator()(const char* s1, const char* s2) const {
    c1 = s1;
    c2 = s2;
    cmpVal = strcmp(s1, s2);
    cmpRet = (cmpVal == 0);
    return cmpRet;
  }
};

// Hash functor.
struct HashChar {

  size_t operator()(const char* str) const {
    hashChar = str;
    size_t hash = 0;
    int c;

    while (c = *str++)
      hash = c + (hash << 6) + (hash << 16) - hash;

    hashVal = hash;
    return hash;
  }
};

void printStatus() {
  printf("'%s' was hashed to: '%lu'\n", hashChar, hashVal);
  printf("strcmp('%s','%s')='%d' and KeyEqual='%d'\n", c1, c2, cmpVal, cmpRet);
}

int main(int argc, char** argv) {

  // Create the unordered map.
  tr1::unordered_map<const char*, int, HashChar, CmpChar > hash_map;
  hash_map["apple"] = 1;
  hash_map["banana"] = 2;
  hash_map["orange"] = 3;

  // Grab the inital hash value of 'apple' to see what it hashes to.
  char buffer[256];
  bzero(buffer, sizeof (buffer));
  strcpy(buffer, "apple");
  if (hash_map[buffer] == 1) {
    printf("First hash: '%s'=1\n", buffer);
  }
  printStatus();

  // Create a random character
  srand((unsigned int) time(NULL));
  char randomChar = (rand() % 26 + 'a');

  // Use the hash 1000x times to see if it works properly.
  for (int i = 0; i < 1000; i++) {

    // Fill the buffer with 'apple'
    bzero(buffer, sizeof (buffer));
    strcpy(buffer, "apple");

    // Try to get the value for 'apple' and report an error if it equals zero.
    if (hash_map[buffer] == 0) {
      printf("\n****Error: '%s'=0 ****\n", buffer);
      printStatus();
    }

    // Fill the buffer with a random string.
    bzero(buffer, sizeof (buffer));
    buffer[0] = randomChar;
    buffer[1] = '\0';

    // Hash the random string.
    // ** Taking this line out removes the error. However, based on the functors
    // it should be acceptable to reuse a buffer with different content.
    hash_map[buffer];

    // Update the random character.
    randomChar = (rand() % 26 + 'a');
  }

  printf("done!\n");

  return EXIT_SUCCESS;
}

1 个答案:

答案 0 :(得分:2)

在容器中使用char *时必须非常小心,因为char *不会像你希望的那样被复制。

通过使用unordered_map的operator [],在地图中用作键的内容不是你想要的字符串。

operator []应该将键插入到映射中,复制它调用默认构造函数(see the reference),在这种情况下,它只是复制缓冲区[0]。

所以之后,你的方法CmpChar会有一个奇怪的行为,因为它在密钥中读取的下一个字节可以是任何东西。

如果使用字符串对象,则不会出现此类问题。