如何解决对为什么我的哈希表代码中有 std::logic_error 感到困惑
我试图通过按年龄组织结构“Student”来显示我的哈希表的索引结构。我不知道如何调试我所拥有的,因为在尝试运行代码时我只剩下:
" 在抛出 'std::logic_error' 实例后调用终止 what(): basic_string::_M_construct null 无效"
我不明白。
这是我的代码的样子:
#include<iostream>
#include<list>
using namespace std;
struct Student {
string name;
int age;
double fee;
Student() {
name = "";
age = 0;
fee = 0.0;
}
Student(string n,int a,double d) {
name = n;
age = a;
fee = d;
}
};
class Hash {
private:
int tableSize;
list<Student>* HT;
public:
Hash(int s) {
this->tableSize = s;
HT = new list<Student>[tableSize];
}
int hashFunction(int key) {
return (key % tableSize);
}
void insert(int key,Student x) {
int index = hashFunction(key);
HT[index].push_back(x);
}
void print() {
for (int i = 0; i < tableSize; i++) {
cout << i;
for (auto x : HT[i]) {
cout << "," << x.age;
}
cout << endl;
}
cout << endl;
}
};
int main() {
Student s1 = Student("s1",25,20.25);
Student s2 = Student("s2",19,25.17);
Student s3 = Student("s3",18,16.72);
Student s4 = Student("s4",11,17.35);
Student s5 = Student("s5",32,18.43);
Student array[5] = { s1,s2,s3,s4,s5 };
Hash HT(7);
int n = sizeof(array) / sizeof(array[0].age);
for (int i = 0; i < n; i++) { HT.insert(array[i].age,array[i]); };
HT.print();
return 0;
}
谁能帮我解释一下这个错误是什么意思,以及如何修复我的代码以便打印出我的哈希表结构?
解决方法
直接问题:
- 您错误地计算了
array
中的元素数量。
应该int n = sizeof(array) / sizeof(array[0].age);
或更好auto n = sizeof(array) / sizeof(array[0]);
auto n = std::size(array);
- 你没有在析构函数中
delete[] HT;
~Hash() { delete[] HT; }
我建议使用 std::vector<std::list<Student>>
而不是进行手动内存管理。它还有一个size()
成员函数,可以省去计算大小的麻烦。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。