简体   繁体   中英

C++ Standard Library hash code sample

I solved a problem to find duplicates in a list

I used the property of a set that it contains only unique members

set<int> s;

// insert the new item into the set
s.insert(nums[index]);

// if size does not increase there is a duplicate
if (s.size() == previousSize)
{
   DuplicateFlag = true;
   break;
}

Now I am trying to solve the same problem with hash functions in the Standard Library. I have sample code like this

#include <functional>

using namespace __gnu_cxx;
using namespace std;

hash<int> hash_fn2;
int x = 34567672;
size_t int_hash2 = hash_fn2(x);

cout << x << "   " << int_hash2 << '\n';

x and int_hash2 are always the same Am I missing something here ?

For std::hash<int> , it's ok to directly return the original int value . From the specification , it only needs to ensure that for two different parameters k1 and k2 that are not equal, the probability that std::hash<Key>()(k1) == std::hash<Key>()(k2) should be very small, approaching 1.0/std::numeric_limits<size_t>::max() . Clearly returning the original value satisfies the requirement for std::hash<int> .

x and int_hash2 are always the same Am I missing something here ?

Yes. You say "I am trying to solve the same problem with hash functions" , but hash functions are not functional alternatives to std::set<> s, and can not - by themselves - be used to solve your poroblem. You probably want to use a std::unordered_set<> , which will internally use a hash table , using the std::hash<> function (by default) to help it map from elements to "buckets". For the purposes of a hash table, a hash function for integers that returns the input is usually good enough, and if it's not the programmer's expected to provide their preferred alternative as a template parameter.

Anyway, all you have to do to try a hash table approach is change std:set<int> s; to std::unordered_set<int> s; in your original code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM