I am currently working on data structures and algorithm semester project in C++. I want to implement a hash function to access a person's data using his name (string) and his phone number (integer). I also plan to handle collisions with open addressing (if this info is relevant). Also, I am not allowed to use any STL library functions.
Asked
Active
Viewed 603 times
0
-
2boost has a handy function [hash_combine](https://www.boost.org/doc/libs/1_75_0/doc/html/hash/combine.html), even if you can't use that directly you can always pinch the source code. – john Jan 05 '21 at 16:19
-
You should start by implementing a hashing function for just a string. Once you have that, there are several possible solutions for hashing over multiple values. – François Andrieux Jan 05 '21 at 16:19
-
1General purpose hash function that can hash any array of bytes, https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function. – john Jan 05 '21 at 16:21
-
You are not asking about a hash of "name + phone" are you? What you mean is that you want to look up in a hash table if you have EITHER only name OR only phone, but not both, don't you? If I am right you can see from the comments above that you need to clarify by [edit]ing your question. – Yunnosch Jan 05 '21 at 16:34
-
@Yunnosch no i wanted to use to keys for example i have two information related to person,One is his name which is in string and other is phone number which is a string.I wanted to used both things as two keys in a hash function to decrease collision.My reason for using phone # is that two person can have the same name but phone# is unique – SomeOne Jan 05 '21 at 16:52
-
I see. I think I was wrong and the older comments do in fact apply. I will leave my comments, as long as I still see the potential that others have my misunderstanding. If you can avoid it by rephrasing I will delete my comment. I thinks they, together with your explanation, help with clarity. But if you want my comments deleted I will. Just let me know. – Yunnosch Jan 05 '21 at 16:56
-
1Your two keys are actually one key. Like how the phone number is one key even though it has 10 digits in it. Well your key is one key even though it has two parts. – user253751 Jan 05 '21 at 16:56
1 Answers
1
A general approach is to:
- Serialise the data into a stream of bytes.
- Create a
std::string_view
of the resulting byte buffer and use its hash
Efficient solution for the step 1. can be tricky to implement since C++ doesn't have standard way to serialise data. A trivial but non-optimal solution is to simply convert to a textual string in which case we don't need a string view either.
In your example, you could use:
std::string data = name + std::to_string(phone);
std::size_t hash = std::hash<std::string>{}(data);
By defining a general hash function, you could stream the bytes of individual objects separately without storing them first in a contiguous buffer.

eerorika
- 232,697
- 12
- 197
- 326