0

我尝试使用 unordered_map 将 char* 键散列为整数值。在编写自定义函子以散列和比较 char* 之后,无序映射似乎可以工作。但是,我最终注意到散列有时会返回不正确的结果。我创建了一个测试项目来重现错误。下面的代码创建了一个带有 char* 键和自定义函子的 unordered_map。然后它运行 1000 次循环并记录发生的任何哈希错误。我想知道我的仿函数是否有问题,或者问题是否出在 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;
}
4

1 回答 1

2

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

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

operator[] 应该将键插入映射,并调用默认构造函数复制它(请参阅参考资料),在这种情况下,它将简单地复制缓冲区 [0]。

因此,之后,您的方法 CmpChar 将有一个奇怪的行为,因为它将在键中读取的下一个字节可以是任何东西。

如果使用字符串对象,就不会出现这样的问题。

于 2013-07-06T20:44:10.787 回答