gpt4 book ai didi

c++ - 如何在 C++ 中查看哈希项?

转载 作者:行者123 更新时间:2023-11-28 08:31:14 25 4
gpt4 key购买 nike

您好,我有以下代码,我希望能够向其中插入单词,并能够通过打印出来查看我放入散列中的内容。这是我拥有的:

#include <iostream>
#include <fstream>
#include <string>
#include <hash_map>
#include <set>
#include <windows.h>

using namespace std;

struct nlist{
struct nlist *next;
char *name;
char *defn;
};

#define HASHSIZE 101

static struct nlist *hashtab[HASHSIZE];

unsigned hash(const char *s)
{
unsigned hashval;

for (hashval = 0; *s != '\0'; s++)
hashval = *s + 31 * hashval;
return hashval % HASHSIZE;
}

struct nlist *lookup(const char *s)
{
struct nlist *np;

for (np = hashtab[hash(s)]; np != NULL; np = np->next)
if (strcmp(s,np -> name) == 0)
return np;
return NULL;
}

struct nlist *install(const char *name, const char *defn)
{
struct nlist *np;
unsigned hashval;

if ((np = lookup(name)) == NULL){
np = (struct nlist *) malloc (sizeof(*np));
if (np == NULL || (np -> name = strdup(name)) == NULL)
return NULL;
hashval = hash(name);
np->next = hashtab[hashval];
hashtab[hashval] = np;
}
else{
free((void *) np->defn);

}
if ((np -> defn = strdup(defn)) == NULL)
return NULL;
return np;
}

int main(){

cout << "yo";
string inline1;
while (1){
getline(cin, inline1);
if (inline1 == "hash"){
getline(cin, inline1);
cout << hash(inline1.c_str()) << '\n';
}
else if (inline1 == "lookup"){
getline(cin, inline1);
cout << lookup(inline1.c_str()) << '\n';
}
else if (inline1 == "install"){
getline(cin, inline1);
string inline2;
getline(cin, inline2);
cout << install(inline1.c_str(), inline2.c_str()) << '\n';
}
}
}

最佳答案

您在这里遇到的问题是,您正在打印指向您已查找的 nlist 项目的指针,而不是其中的 defn 字符串的值那个项目。

在您的主循环中,您有以下代码:

else if (inline1 == "lookup"){
getline(cin, inline1);
cout << lookup(inline1.c_str()) << '\n';
}

您可能想要的是:

else if (inline1 == "lookup"){
getline(cin, inline1);
cout << lookup(inline1.c_str())->defn << '\n';
}

关于c++ - 如何在 C++ 中查看哈希项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1959927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com