c++ - 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;
}
解决方案
推荐阅读
- azure - 未找到 QnA Maker 知识库
- reactjs - 有没有办法处理Antd Upload中删除按钮的onClick?
- python - 修复此列表的最pythonic /最有效的方法是什么?
- xml - 为什么这个 XPath 表达式无效?
- python-3.x - 用于 lastLogin 访问 ArcGIS Portal 的 Python 3 arcgis.gis.user
- c# - 为什么前置通道规范不起作用?
- python - Python在构建子列表时从列表中删除并合并重复的字典
- python - AttributeError:'numpy.ndarray'对象在循环时没有属性'between'
- nginx - Nginx“direct_io”和“sendfile”效果
- python - 如何防止触发多个错误实例?discord.py 重写