A
A
Artem2015-08-12 01:54:50
Qt
Artem, 2015-08-12 01:54:50

How to correctly compose the qHash function for an object containing two QStrings? Or just what is the algorithm for hashing two strings?

You need to push a custom data type into the QSet, which consists of two QStrings, something like:

class Mynametype {
public:
    QString firstName;
    QString lastName;
};

To do this, you need to write a qHash function. Interested in the algorithm for obtaining a non-repeating hash of two strings. C++/Qt code is not required, I'll write it myself if I know how to calculate it.
Features of lines (if it is important):
The first line and the second line - whatever, but not large (let's say up to 100 characters, although the average is 10, 20 maximum).
It is also necessary that there is not a simple concatenation and its hash, as it is necessary that different pairs of firstName lastName have different hashes, even if the string concatenation is the same. That is, if there is, say, a full name "Abdul Karim Jabar", then
objects of type Mynametype c and these are DIFFERENT objects, despite the fact that the concatenation of firstName + lastName is equal.{ firstName="Abdul ", lastName="Karim Jabar" }{ firstName="Abdul Karim", lastName=" Jabar" }
So far, it only occurred to me to make a concatenation and put some kind of separator character in the middle and hash such a string with the method already available in Qt. Type: But even I'm not sure that this is a normal way, so rate it normally will work or mb in some cases not. Yes, and I would like something more elegant, especially from an algorithmic point of view. Generally speaking, the original data type is not related to names and is just two different strings. If anything, then spaces and other non-alphabetic characters should not go anywhere and are compared on a general basis, i.e. for example, a line with them at the end or in the middle and without them are DIFFERENT lines.
return qHash(firstName+"|"+lastName);

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Stanislav Makarov, 2015-08-12
@Nipheris

And why such a strange need for a UNIQUE hash (which by the way, in principle, you will not get for two lines of 20 characters, since the hash value is of the uint type)?
> these are DIFFERENT objects, despite the fact that the concatenation of firstName + lastName is equal.
well, let it match once, not such a frequent case for a first and last name. Will you have a thousand such Karims with the same concatenated name?

P
Pavel K, 2015-08-12
@PavelK

I did the same for myself as you did.
gluing, and between them a separator. works fast enough.

V
Vitaly, 2015-08-12
@vt4a2h

Take the hash from each line and do an xor. Well, if the lines are the same, then don't do xor.
And you can also look in the direction of boost hash, for example.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question