[英]Converting C# hash function to C++
I have this function in C#: 我在C#中具有以下功能:
public static unsafe int GetMonoHash(string str) {
unsafe {
fixed (char* src = str) {
char* chPtr2 = src; // + offset;
char* chPtr3 = (chPtr2 + str.Length) - 1;
int num = 0;
while (chPtr2 < chPtr3) {
num = ((num << 5) - num) + chPtr2[0];
num = ((num << 5) - num) + chPtr2[1];
chPtr2 += 2;
}
chPtr3++;
if (chPtr2 < chPtr3) {
num = ((num << 5) - num) + chPtr2[0];
}
return num;
}
}
}
I tried to rewrite it in C++ and I got this far: 我试图用C ++重写它,而我到了这一步:
int Utils::getMonoHash(std::string str)
{
char* src = &str[0];
char* chPtr2 = src; // + offset;
-> char* chPtr3 = (chPtr2 + str.length) - 1;
int num = 0;
while (chPtr2 < chPtr3) {
num = ((num << 5) - num) + chPtr2[0];
num = ((num << 5) - num) + chPtr2[1];
chPtr2 += 2;
}
chPtr3++;
if (chPtr2 < chPtr3) {
num = ((num << 5) - num) + chPtr2[0];
}
return num;
}
This was throwing a compilation errors: 这引发了编译错误:
C3867 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>::length': non-standard syntax; use '&' to create a pointer to member
C2297 '+': illegal, right operand has type 'unsigned __int64 (__cdecl std::basic_string<char,std::char_traits<char>,std::allocator<char>>::* )(void) noexcept const'
So I changed the indicated ( ->
) line to 所以我将指示的(
->
)行更改为
char* chPtr3 = (chPtr2 + (char *)str.length) - 1;
which gave me a new compilation error (just one this time, yay!): 这给了我一个新的编译错误(这次只是一次,是的!):
C2440 'type cast': cannot convert from 'unsigned __int64 (__cdecl std::basic_string<char,std::char_traits<char>,std::allocator<char>>::* )(void) noexcept const' to 'char *'
I have no idea what to do now. 我不知道该怎么办。 I need the C++ function to have the same output as the C# one when given the same input as the C# one.
当给定与C#相同的输入时,我需要C ++函数具有与C#相同的输出。
What do I do here? 我在这里做什么?
str.length is not a property, it is a function and needs () str.length不是属性,它是一个函数,需要()
In my experience as a C# programmer, this is one of the most common mistakes C# programmers make when writing C++. 以我作为C#程序员的经验,这是C#程序员在编写C ++时犯的最常见错误之一。
Don't forget parenthesis after str.length. 不要忘记str.length之后的括号。 Correct type should be like this
正确的类型应该是这样
char* chPtr3 = (chPtr2 + str.length()) - 1;
What do you do? 你是做什么? You stop "translating" as if C++ and C# have anything in common, and write from scratch using your base requirements — and your C++ book — as a guide.
您将停止“翻译”,就好像C ++和C#有共同之处一样,并使用您的基本要求(以及C ++书籍)作为指南从头开始编写。
In this case your problem is that you are using a member function incorrectly. 在这种情况下,您的问题是您使用的成员函数不正确。 It is
str.length()
. 它是
str.length()
。 The compiler's complaints are about using a function name incorrectly, without actually calling it. 编译器的抱怨是关于错误使用函数名,而没有实际调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.