c++ - 指针比较问题

标签 c++ pointers hash linked-list

我在使用指针时遇到问题,无法绕过它..

在 HashTable 实现中,我在每个桶中都有一个有序节点列表。我遇到的问题是在插入函数中,在比较中查看下一个节点是否大于当前节点(以便插入该位置(如果是)并保持顺序。

你可能会觉得这个散列实现很奇怪,但我需要能够进行大量查找(但有时也很少)并计算重复次数(如果它已经插入)(所以我需要快速查找,因此 Hash ,我曾将自平衡树视为 AVL 或 R-B 树,但我不了解它们,所以我采用了我知道如何实现的解决方案……它们对于此类问题的速度更快吗?),但我也我完成后需要按顺序取回它们。 之前我有一个简单的列表并检索数组,然后进行快速排序,但我认为我可以通过保持列表有序来改进事情。

我必须映射的是一个 27 位无符号整数(最准确的是 3 个 9 位数字,但我将它们转换为一个 27 位数字,同时进行 (Sr << 18 | Sg << 9 | Sb)它们的值为 hash_value。如果您知道将 27 位 int 映射到 12-13-14 位表的好函数,请告诉我,我目前只做典型的 mod prime 解决方案。

这是我的 hash_node 结构:

class hash_node {
public:
  unsigned int hash_value;    
  int repetitions;
  hash_node *next;                       

  hash_node(  unsigned int hash_val,
                     hash_node *nxt);
 ~hash_node();  
};

这就是问题的根源

void hash_table::insert(unsigned int hash_value) {

unsigned int p = hash_value % tableSize;
if (table[p]!=0) { //The bucket has some elements already
hash_node *pred; //node to keep the last valid position on the list
    for (hash_node *aux=table[p]; aux!=0; aux=aux->next) {
            pred = aux; //last valid position
        if (aux->hash_value == hash_value ) {
                 //It's already inserted, so we increment it repetition counter
                 aux->repetitions++; 
            } else if (hash_value < (aux->next->hash_value) ) { //The problem
                    //If the next one is greater than the one to insert, we 
                    //create a node in the middle of both.
        aux->next = new hash_node(hash_value,aux->next);
        colisions++;
                    numElem++;
                 }
     }//We have arrive to the end od the list without luck, so we insert it after 
     //the last valid position
 ant->next = new hash_node(hash_value,0);
 colisions++;
     numElem++;
 }else { //bucket it's empty, insert it right away.
    table[p] = new hash_node(hash_value, 0);
    numElem++;
 }

这是 gdb 显示的内容:

Program received signal SIGSEGV, Segmentation fault.
0x08050b4b in hash_table::insert (this=0x806a310, hash_value=3163181) at ht.cc:132
 132                    } else if (hash_value < (aux->next->hash_value) ) {

这有效地表明我正在将内存地址与值进行比较,对吗? 希望很清楚。再次感谢!

最佳答案

aux->next->hash_value

没有检查“next”是否为 NULL。

关于c++ - 指针比较问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5007483/

相关文章:

c++ - 对象的分离构造和克隆

perl - 遍历 perl 中的哈希值

pointers - Golang 指向值的指针字符串

c++ - wcscat_s 函数 - 缓冲区错误

c - 尝试在 C 中分配和调用嵌套结构的值时出现“段错误”错误

string - 基于预先计算的散列比较字符串距离

python - 如何使用哈希进行密码检查?

c++ - mysql-connector-c++ - ‘get_driver_instance’ 不是 ‘sql::mysql’ 的成员

c++ - CPack 具有自己依赖项的多个包

c++ - 使用 SFML 和 Qt 窗口不显示