c++ - 当我尝试在 C++ 中 push_back 一个项目时,为什么会出现段错误?

标签 c++ hashmap hashtable hashcode

<分区>

我正在为我的数据结构类(class)开发哈希表实验室。当我在插入函数中使用 push_back() 函数时,我不断收到一个我认为会发生的设置错误。但是,我不确定是什么导致了这个错误。

    using namespace std;

    HashTable::HashTable(int buckets) {
        this->buckets = buckets;
        vector<Entry>* table = new vector<Entry>[buckets];
    }


    Entry HashTable::insert(GameBoard board, int number) {
        int index = compress(board.hashCode());
        Entry entry = Entry(board, number);
        table[index].push_back(entry);
        return entry;
    }


    int HashTable::compress(int hashCode) {
        return (hashCode % buckets);
    }


    Entry::Entry(GameBoard board, int value) { 
        this->board = board; 
        this->value = value; 
    }


    int GameBoard::hashCode() {

        int hashVal = 0;

        for (int r = 0; r < DIMENSION; r++) {
            for (int c = 0; c < DIMENSION; c++) {
                hashVal = ((127 * hashVal) + board[r][c]) % 16908799;
            }
        }

        return hashVal;
    }

最佳答案

在您的问题中显示的代码中:

HashTable::HashTable(int buckets) {
    this->buckets = buckets;
    vector<Entry>* table = new vector<Entry>[buckets];
}

你创建了一个局部变量table这是指向 vector<Entry> 的指针然后泄漏该内存。然后在HashTable::insert你尝试访问成员变量 table这是未初始化的。

关于c++ - 当我尝试在 C++ 中 push_back 一个项目时,为什么会出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29997100/

相关文章:

java - 哈希表替代品

c++ - 与 pdpotrf 参数混淆

C++ 就地构造和后续销毁 : how do I get the right pointer?

c++ - 可以在头文件中声明 const vector 吗?

java - 在 HashMap 中多次使用键时无限循环

c++ - 在 C++ 中实现哈希表

c++ - 字符串到 SecByteBlock 的转换问题

java - JSTL 访问 HashMap 中的整数/长键

ruby - 从哈希中随机化键值对

javascript - 如何在 JavaScript 中进行关联数组/散列