检查哈希表中的重复项

史蒂文

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

这个逻辑错误出现在我的第二个 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来比较字符串。比较指向字符的指针是否相等会告诉您两个指针是否相等,而不是它们是否指向相同的字符串。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章