I have to write my own hash function. If I wanted to just make the simple hash function that maps each letter in the string to a numerical value (i.e. a=1, b=2, c=3, ...), is there a way I can perform this hash on a string without having to first convert it to a c-string to look at each individual char? Is there a more efficient way of hashing strings?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- how to split a list into a given number of sub-lis
- thread_local variables initialization
相关文章
- JSP String formatting Truncate
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
Another way for small strings:
You can examine each individual char from a std::string using the
[]
operator. However, you can look at Boost::Functional/Hash for guidance on a better hashing scheme. There is also a list of hashing functions in c located here.Re the first question, sure, e.g, something like:
regarding the second, there are many better ways to hash strings. E.g., see here for a few C examples (easily translatable to C++ along the lines of the snippet above).
xor the characters together, four at a time.
Here's a C (++) hash function that I found in Stroustrup's book:
If you're using it for a hash table (which Stroustrup does) then you can instead return the abs of the hash modulo a prime number. So instead
for the last line.
You can make use of the member functions operator[] or at of the string class or iterators to access individual char of a string object without converting it to c-style char array.
To hash a string object to an integer you'll have to access each individual char of the string object which you can do as: