【问题标题】:Return the size of the hash table?返回哈希表的大小?
【发布时间】:2015-10-19 21:26:39
【问题描述】:

如果我解释不清楚,请提前原谅.. 好的,所以我已经使用这样的向量声明了一个哈希表:

> 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;
}

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

【问题讨论】:

    标签: c++ vector size hashtable


    【解决方案1】:

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

    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 - 我在此处插入了关键字,以便您知道该放在哪里,并在定义tablesize() 时在上面使用它。


    如果您真的决心避免使用额外的成员变量,您也可以这样做...

    int HashTable::tablesize() const {
        int size = 0;
        for (std::vector<std::string>& vs : arrayOfBuckets)
            size += vs.size();
        return size;
    }
    

    ...但是大多数用户会期望一个恒定时间和快速的 size() 函数:他们可能每次都通过循环调用它,所以保持便宜。

    【讨论】:

    • 你先生,刚刚让我免于为这个单人作业而感到压力。谢谢!
    • @JoeDavis:不客气——祝你的课程好运。干杯。 (小提示——如果你用 C++ 来标记它,你可能会得到更多帮助,而且速度更快)
    猜你喜欢
    • 2011-12-10
    • 2014-07-10
    • 2013-03-29
    • 2015-07-13
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 2015-04-24
    • 1970-01-01
    相关资源
    最近更新 更多