返回哈希表的大小?

时间:2015-10-19 21:26:40

标签: c++ vector size hashtable

请原谅我,如果我没有解释清楚...... 好的,所以我使用像这样的向量声明了一个哈希表:

> class HashTable{

    private:
        vector<string> arrayofbuckets[100];

    public:
         void insertelement(string input);
         void deleteelement(string remove);
         bool lookupelement(string search);
         int tablesize();

> }; // end of class

我还使用switch语句创建一个菜单,将元素插入到哈希表中:

> case 'I':
{
        cout << " Which element would you like to insert?: ";
        cin >> Element;

        hash.insertelement(Element);

        }
    break;

然后传递给这个函数:

void HashTable::insertelement(string input){

    int hashValue = 0;

    for(int i = 0; i<input.length(); i++){

        hashValue = hashValue + int(input[i]);

    }

    hashValue = hashValue % 100;
    arrayofbuckets[hashValue].push_back(input);

    cout << " The element " << input << " has been put into value " << hashValue << ends;
}

有没有人知道如何编写一个函数来获取和显示表的大小?

1 个答案:

答案 0 :(得分:0)

最好的方法是跟踪应该初始化或修改它的函数内部的大小:

HashTable::HashTable() : size_(0) { }

void HashTable::insertelement(string input){
    ...do all the existing stuff...
    ++size_;
}

// similarly --size_ inside deleteelement...

int HashTable::tablesize() const { return size_; }

确保添加int size_;数据成员。

请注意bool lookupelement(string search) const;int tablesize() const;应为const - 我已在此处插入关键字,以便您知道放置它的位置,并在定义{{1}时使用上面的内容}。

如果您 确实 决定避免额外的成员变量,您也可以这样做......

tablesize()

...但是大多数用户都希望有一个恒定时间和快速int HashTable::tablesize() const { int size = 0; for (std::vector<std::string>& vs : arrayOfBuckets) size += vs.size(); return size; } 功能:他们可以每次通过循环调用它,所以保持便宜。