您好,我正在尝试实现put,ease,hashCodeSimple,hashCodePoly和hashCodeCyclic函数。该程序可以运行,但是与我应该遇到的冲突相去甚远。例如:我应该获得hashCodePoly 214次冲突,但我却获得0次冲突。
void
HashMap::put(string key)
{
int tempIndex = hash(key); //find index to put the key
this->table[tempIndex]->push_back(key); //point to the index and add another key
this-> inserts[tempIndex]++; //update the size of the array, add one
}
void
HashMap::erase(string key){
int tempIndex = this->hash(key); //point to the index for the key
if(find(key) != -1) //if the key is negative one it is not in the array
{
this->table[tempIndex]->pop_back(); //pushes the index back by one
****this-> inserts[tempIndex] - 1;**** *(says expression result is unused here)* //decrease size of the array to one less
}
int
HashMap::hashCodePoly(string key) const
{
int p= 0;
int a = 0;
int n; //get size of key
n = sizeof(key);
for(int i =0; i < n; i++){
// p = ((int) key[i] -96) * pow(a,key.length()) + p; ?
p = a * int(key[i] - 96); //subtract 96 to convert to numbers
}
return p;
}
int
HashMap::hashCodeSimple(string key) const
{
int h = 0;
int p = 0; //initialize to zero
int n = sizeof(key); //determine the size of the key
for(int i =0; i < n; i++)
{
h = (37 * p) + key[i]; //multiply by constant
}
return h;
}
int
HashMap::hashCodeCyclic(string key) const
{
int len = 0; //variable for the length of integer bit
unsigned int h = 0; //initialize to zero
for (int i=0; i < len; i++){
h = (h<<5) | (h>>27); // 5 bit cyclic shift
h+= (unsigned int)key[i]; //add in next character
}
return h; //return the int h
}
表达式this-> inserts[tempIndex] - 1;
取值的副本存储在this->inserts[tempIndex]
中,并且得到的值是前者减去1
的值。它无能为力,没有副作用,也没有更改存储在任何变量中的值。
由于您对表达式的结果不做任何事情,因此该表达式实际上什么也不做。编译器警告您,这可能不是您要执行的操作。
确实,您似乎希望将值[[存储在this->inserts[tempIndex]
]中减少1
。减小存储值的运算符不是-
,而是-=
或--
。
this->inserts[tempIndex]--;
或
this->inserts[tempIndex] -= 1;
两者实际上都有副作用,因此编译器不会警告您未使用表达式this->inserts[tempIndex]--
的结果(这是在执行this->inserts[tempIndex]
之前存储在--
中的值)或this->inserts[tempIndex] -= 1
(是对this->inserts[tempIndex]
的引用)。