检查哈希中的重复项 table

check for duplicate in hash table

我正在尝试读取一个文件,每个字符串将少于 30 个,并且在数千个字符串中将有 20 个唯一序列。我们正在计算唯一值在哈希 table 中出现的次数。我在处理碰撞时遇到问题。我将所有 char[] 值初始化为“0”,但是 if(protiens[key].protien == “0”) 无法检查结构中的那个位置是否具有值“0”或我的 protiens 之一总是 "ABCDJ..." 超过 10 个字符且少于 30 个字符。所以我认为将所有初始化为“0”将是一种查看我是否已经在结构中放置了 protien 的方法。

这个逻辑错误出现在我的第二个 if 语句中。

这是我们应该使用的算法,然后是我的代码。

While(there are proteins)
 Read in a protein
 Hash the initial index into the proteins table
 While(forever)
   If(found key in table)
    Increment count
    Break;
   If(found empty spot in table)
    Copy key into table
    Increment count
    Break;
   Increment index; // collision! Try the next spot!

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>

using namespace std;

//struct to hold data and count
struct arrayelement 
{
  char protien[30] {"0"};
  int count;
};
arrayelement protiens[40];

//hash function A=65 ascii so 65-65=0 lookup table = A=0,B=1... 
//h(key) = ( first_letter_of_key + (2 * last_letter_of_key) ) % 40

int getHashKey(char firstLetter, char lastLetter)
{
   return ((int(firstLetter) - 65) + (2 * (int(lastLetter) - 65))) % 40;
}


int main()
{
   fstream file;
   string filename;
   char word[30];
   int key;

   filename = "proteins.txt";

    //open file
    file.open(filename.c_str());

    //while not eof
    while (file >> word)
    {
       //get key
       key = getHashKey(word[0], word[strlen(word)-1]);

        //loop "forever" no difference if i use 1 or 10000000 besisdes run time????
    for (int j = 0; j < 1; j++)
    {
        //if found key in table
        if (protiens[key].protien == word)
        {
            protiens[key].count++;
            break;
        }

        //if found empty spot in table
        //if(protiens[key].protien == "0") i intialized all protiens to "0" why would this not work for 
        //checking if i put a protien there already or not
        else
        {
            strcpy_s(protiens[key].protien, word);
            protiens[key].count++;
            break;
        }

        //collison incrment key
        key = getHashKey(word[0], word[strlen(word) - 1]) + 1;

    }

}
//print array of uniques with counts
for (int j = 0; j < 40; j++)
{
    cout << j << "\t" << protiens[j].protien << "\t" << protiens[j].count << endl;
}

}

    //if(protiens[key].protien == "0") i intialized all protiens to "0" why would this not work for 
    //checking if i put a protien there already or not

因为"0"是常量而protiens[key].protien是指向变量的指针,所以它们不可能相等。

想象一下,如果它们相等。这意味着 protients[key].protien[0]='Q';"0"[0]='Q'; 完全相同。但前者非常有意义,改变了一个变量。而后者是疯了,修改一个常量。

我不知道为什么当你有 std::string 时你会这样使用字符数组。但如果你非要这样,就用strcmp来比较字符串吧。比较指向字符的指针是否相等会告诉您两个指针是否相等,而不是它们是否指向相同的字符串。