首页 > 解决方案 > C++模板类中的段错误

问题描述

我是 C++ 新手,我正在尝试实现自己的哈希表。该问题出现在类的 add 方法中。它在我的 Mac 上完美运行,但是当我尝试在运行 ubuntu 的计算机上运行它时,它会出现故障。当我使用整数而不是 std::string 类时,这也可以正常工作。

这是main中的代码:

Hash<string> * load(string filename);
int main(void) {
    Hash<string> *dict = load("words.txt");
    
}
Hash<string> * load(string filename) {
    ifstream in = ifstream(filename);
    if (!in) {
        throw FileNotFoundError();
    }
    Hash<string> * hash = new Hash<string>(hashfunction);
    string buff;
    while(in >> buff) {
        hash -> add(buff);
    }
    in.close();
    return hash;
}

问题出现在 Hash 类的 add 方法中

template <typename T>
class Hash {
private:
    int size;
    Node<T> **nodes;
    int (*hash)(T obj);
    int arrsize;
    static int constexpr const standard = 1000000;
public:
    Hash(int (*hash)(T obj), int arrsize = standard)
        :hash(hash),arrsize(arrsize),size(0){
            nodes = new Node<T> *[arrsize];
            for (int i = 0; i < arrsize; i++) {
                nodes[i] = nullptr;
            }

    }
    bool add(T &&obj) {
        add(obj);
    }
    bool add(T &obj) {
        size_t code = hash(obj) % arrsize;
        Node<T> *n = new Node<T>(obj, nodes[code]);
        nodes[code] = n;
        size ++;
        return true;
    }

这是供参考的节点类

template  <typename T>
class Node {
private:
    T obj; 
    Node *next;
    friend bool operator==(Node &left, T& obj) {
        return left.obj == obj;
    }
public:
    Node(T obj)
        :Node(obj, nullptr){

    }
    Node(T obj, Node *next) 
        :obj(obj),next(next) {

    }
    void deleter() {
        if (next) {
            next -> deleter();
        }
        delete this;
    }
    Node * getNext() {
        return next;
    }
    void setNext(Node * next) {
       this -> next = next;
    }

};

哈希函数

//Uses Hash function djb2 by Dan Bernstein http://www.cse.yorku.ca/~oz/hash.html
int hashfunction(string words){
    unsigned long hash = 5381;
    int c;
    const char *word = words.c_str();
    while ((c = *word++))
        hash = ((hash << 5) + hash) + tolower(c); /* hash * 33 + c */
    return hash;
}

标签: c++segmentation-fault

解决方案


推荐阅读