如何将信息从txt文件添加到哈希表

时间:2019-05-01 02:00:39

标签: c++

如何实现addInfo函数。我们必须使用链接哈希函数根据行的编号查找和排序行。但是在我需要做addInfo之前。 例如:第一行“ 1009 1“ Royal Queen” 2015 160” 序列号是1009,如果还有其他船舶的序列号以9结尾,我们必须将它们一起显示。 这是我到目前为止的代码:

#include <iostream>
#include <fstream>
using namespace std;
struct ShipRecord
{
    int serialNum;
    int shipType;
    string name;
    int year;
    int cap;
    ShipRecord *next;
    ShipRecord(int x)
    {
        serialNum = x;
        next = nullptr;
    }
};
const int SIZE = 10;
class HashMgr
{
    ShipRecord *head = nullptr;
    ShipRecord *tail = nullptr;
public:
    HashMgr()
    {
        ShipRecord * hashTable[SIZE] = {nullptr};

        string line;
        ifstream myfile;
        myfile.open("shipRecords.txt");
        if(myfile.is_open())
        {
            while (!myfile.eof())
            {
                getline (myfile, line);
                addInfo(line);
            }
            myfile.close();
        }
    }
addInfo(string line)
    {}
displayOne(int serialNum)
    {}
displayAll()
    {}
int main()
{
    HashMgr hm;
    hm.displayAll();
    hm.displayOne(1009);
    hm.displayOne(1010);
    hm.displayOne(1019);
    hm.displayOne(1029);
    hm.displayOne(1039);
    hm.displayOne(1014);
    hm.displayOne(1008); /// Prompt a message to that the record does not exist
    hm.deleteOne(1009);
    hm.deleteOne(1039);
    hm.displayAll();
    return 0;
}
/*
Here is the txt.file
  1009 1 "Royal Queen"     2015 160
 1010   2  "Carnival"        2016  1600
 1019  1  "Ocean King"       2013  110
 1029 2 "Royal Prince"     2012 2000
 1039 2 "Royal Princess"  2010 2100
 1014 2 "Royal Caribbean" 2016 1600
*/

1 个答案:

答案 0 :(得分:0)

我建议您使用带有散列函数的键创建散列表,散列表号为number%10,值应为ShipRecord *,但指向vector。

遍历文件时,请继续基于哈希函数求值添加新元素以更正向量。