Return 散列的大小 table?
Return the size of the hash table?
如果我没有解释清楚,请提前原谅..
好的,我已经使用像这样的向量声明了一个散列 table:
> 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 语句将元素插入哈希 table:
> 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;
}
有谁知道如何编写函数来获取和显示 table 的大小?
最好的方法是跟踪应该初始化或修改它的函数内部的大小:
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
- 我在这里插入了关键字所以你知道把它放在哪里,并在上面定义 [= 时使用它16=].
如果你真的决心避免额外的成员变量,你也可以这样做...
int HashTable::tablesize() const {
int size = 0;
for (std::vector<std::string>& vs : arrayOfBuckets)
size += vs.size();
return size;
}
...但大多数用户会期望一个恒定时间且快速的 size()
函数:他们可能每次在循环中调用它,所以保持便宜。
如果我没有解释清楚,请提前原谅.. 好的,我已经使用像这样的向量声明了一个散列 table:
> 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 语句将元素插入哈希 table:
> 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;
}
有谁知道如何编写函数来获取和显示 table 的大小?
最好的方法是跟踪应该初始化或修改它的函数内部的大小:
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
- 我在这里插入了关键字所以你知道把它放在哪里,并在上面定义 [= 时使用它16=].
如果你真的决心避免额外的成员变量,你也可以这样做...
int HashTable::tablesize() const {
int size = 0;
for (std::vector<std::string>& vs : arrayOfBuckets)
size += vs.size();
return size;
}
...但大多数用户会期望一个恒定时间且快速的 size()
函数:他们可能每次在循环中调用它,所以保持便宜。