【问题标题】:Function returning simple hashcode in C++在 C++ 中返回简单哈希码的函数
【发布时间】:2013-12-22 22:12:24
【问题描述】:

我正在尝试处理我的 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) << "\n\n";

    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 &gt;= length)。因此它通常应该触发for循环,不是吗?非常感谢这里的一点提示!

干杯!

【问题讨论】:

  • 如何为std::hash 使用适当的专业化??
  • 是的,这可能是正常的处理方式。我在我的 C++ 基础书籍的第 9 章,这是关于传递参数和返回值的。我认为重点是用我目前学到的东西来解决这些任务。
  • for (a;b;c) 中,表达式b 需要为true 才能执行循环迭代,它应该产生false 来终止循环。看来你搞反了。

标签: c++ for-loop parameter-passing return-value hashcode


【解决方案1】:

一个惯用的for循环应该是这样的:

for(index = 0; index < length; ++index)
{
    hash_value += string[index];
}

主要特点是索引从 0 开始(index = 0),索引与长度比较,“小于”(index &lt; length),正如您所拥有的那样,索引使用 pre 递增-增量(++index)。

【讨论】:

  • 该死,我不敢相信我已经花了最后一个小时来掌握这个窍门......当然......谢谢!
【解决方案2】:
for(index = 0; index < length; ++index)

您目前从未进入循环,并且没有字符导致我的系统出现分段错误。它在唯一通过条件(length &gt;= index,即 0 >= 0)的情况下进入循环,然后循环直到它尝试访问非法位置,此时发生 seg 错误。

【讨论】:

  • 你能改进你对段错误的解释吗?
  • ugh... C 字符串应以 0 结尾。所以访问空字符串的第 0 个字符就可以了……不知道你所说的段错误是什么意思。
  • 如果段错误的原因是错误的,那么我很乐意将其删除,但是当我构建并运行示例时它肯定会导致段错误。
  • 已更正。我对\0 导致段错误感到困惑,在考虑它(并修改我的版本)之后显然不是这样。感谢您的指导。
猜你喜欢
  • 2013-01-02
  • 2017-12-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-22
  • 1970-01-01
  • 2014-11-14
  • 2013-02-13
  • 2019-07-27
相关资源
最近更新 更多