在C++中返回简单哈希码的函数
Function returning simple hashcode in C++
我正在尝试处理我C++书中的以下编程练习:"编写一个函数,该函数将字符串作为参数并返回原始哈希代码,该代码是通过将字符串中所有字符的值相加来计算的。
我的解决方案是:
#include <iostream>
#include <string>
#define clrscr() system("cls")
#define pause() system("pause")
using namespace std;
int hashc(char string[]);
int main()
{
char phrase[256];
cout << "This program converts any string into primitve hash-code." << "n";
cout << "Input phrase: "; cin.getline(phrase, sizeof(phrase));
cout << "n";
cout << "Hash-code for your phrase is: " << hashc(phrase) << "nn";
pause();
return(0);
}
int hashc(char string[])
{
int index;
int length;
int hash_value = 0;
length = strlen(string);
for(index = 0; index >= length; ++index)
{
hash_value = hash_value + string[index];
}
return(hash_value);
}
问题是:该函数总是返回hash_value = 0
,因为它似乎跳过了for循环。当我在函数中返回length
时,它会返回给定字符串的正确长度(对于index = 0
index >= length
)。因此,它通常应该触发 for 循环,不是吗?非常感谢这里的一点提示!
干杯!
惯用的 for 循环应如下所示:
for(index = 0; index < length; ++index)
{
hash_value += string[index];
}
主要特点是索引从0(index = 0
)开始,索引与长度"小于"(index < length
)进行比较,并且,正如你所拥有的,索引使用预递增(++index
)递增。
for(index = 0; index < length; ++index)
您目前从未进入循环,并且没有字符导致我的系统上出现分段错误。它进入循环的唯一情况是它通过条件(length >= index
,即0>= 0),然后循环,直到它试图访问非法位置,此时发生seg错误。
相关文章:
- 如何为位集找到/实现一个好的哈希函数
- 对于短字符串来说,这是一个很好的哈希函数吗?
- 我在C++中使用提升哈希函数将 3 个双精度组合成一个面临冲突的哈希
- 无冲突的哈希函数
- 在 C++ 中为特定哈希表创建插入函数
- Qt5 哈希函数在 Windows 7 和 Windows10 上不会返回相同的哈希
- 解决由于在哈希函数中使用了不完整的类型而导致的编译失败
- 在C++中返回简单哈希码的函数
- 在C++中是否已经为文件系统迷你过滤器驱动程序编写了一个计算MD5哈希的函数
- 多项式哈希码导致负数
- hash_set哈希器函数
- 调用哈希类函数
- 哈希图实现:---哈希码
- 用于哈希的哈希集函数
- 如何在c++中获得字符串的哈希码
- 用于生成密码哈希的C/ c++函数(使用MD5或其他算法)
- unordered_map自定义哈希/相等函数 - 函数不会被调用
- (C++) 无法迭代密钥哈希器函数中的向量
- 在我的情况下,我如何重载相等的方法以使不同的对象在unordered_multimap具有相同的哈希码值
- 为什么这个哈希表函数显示编译错误