我是散列的新手,所以我想创建一个包含字符串数组的散列表。它在类本身中工作,但是当我尝试在类之外使用字符串数组时,它崩溃了。我的构造函数或我认为的数组有些奇怪。
我把 main.cpp 中的代码粘贴到构造函数中,它没有问题。控制台可以显示我的阵列。但是当我尝试在 main.cpp 中使用 getArray 函数时它崩溃了。
哈希表.h
class hashtable
{
public:
hashtable();
void remove(string);
int hashfunction(string str);
string* getArray();
private:
int table_size;
string* T;
};
哈希表.cpp
hashtable::hashtable()
{
int table_size = 10;
elemts_in_array = 0;
string array[10];
// Im adding some elements to test it. In final Version i will delete the next two lines.
array[0]="start";
array[9]="end";
T = array;
// now I am testing if my function string* getArray() is working, and it's working when i dont use it in main.cpp
string* arraytest = getArray();
for (int i=0; i< 10;i++)
{
cout << i << " - " << arraytest[i]<< endl;
}
}
/////////// getArray function
string* hashtable::getArray()
{
return T;
}
主程序
int main()
{
hashtable table;
string* array = table.getArray();
for (int i=0; i< 10;i++)
{
cout << i << " - " << array[i]<< endl;
}
return 1;
}
当我只创建一个名为 hashtable 的对象时,它的工作没有任何问题,但是当我创建一个对象并且我想通过我的 getArray 函数将数组交给 main.cpp 时,它崩溃了,我真的不知道为什么。
array
在hashtable
的构造函数末尾超出范围并T
指向无效内存。如果您希望 指向的数组T
继续存在于hashtable
的构造函数范围之外,则需要动态分配。或者更好的是,使用std::vector<std::string>
:
class hashtable
{
public:
hashtable()
: T{10}
{
T[0] = "start";
T[T.size() - 1] = "end";
for (int i = 0; i < T.size(); ++i)
{
std::cout << i << " - " << T[i] << '\n';
}
}
std::vector<std::string>& getArray()
{
return T;
}
void remove(std::string);
int hashfunction(std::string str);
private:
std::vector<std::string> T;
};
int main()
{
hashtable table;
std::vector<std::string>& array = table.getArray();
for (int i = 0; i < array.size(); ++i)
{
std::cout << i << " - " << array[i] << '\n';
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句