hashing_examples.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. ///////////////////////////////////////////////////////////////
  2. // Copyright 2012 John Maddock. Distributed under the Boost
  3. // Software License, Version 1.0. (See accompanying file
  4. // LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt
  5. #include <boost/multiprecision/cpp_int.hpp>
  6. #include <boost/random.hpp>
  7. #include <boost/functional/hash.hpp>
  8. #include <unordered_set>
  9. #include <city.h>
  10. //[hash1
  11. /*`
  12. All of the types in this library support hashing via boost::hash or std::hash.
  13. That means we can use multiprecision types directly in hashed containers such as std::unordered_set:
  14. */
  15. //]
  16. void t1()
  17. {
  18. //[hash2
  19. using namespace boost::multiprecision;
  20. using namespace boost::random;
  21. mt19937 mt;
  22. uniform_int_distribution<uint256_t> ui;
  23. std::unordered_set<uint256_t> set;
  24. // Put 1000 random values into the container:
  25. for(unsigned i = 0; i < 1000; ++i)
  26. set.insert(ui(mt));
  27. //]
  28. }
  29. //[hash3
  30. /*`
  31. Or we can define our own hash function, for example in this case based on
  32. Google's CityHash:
  33. */
  34. struct cityhash
  35. {
  36. std::size_t operator()(const boost::multiprecision::uint256_t& val)const
  37. {
  38. // create a hash from all the limbs of the argument, this function is probably x64 specific,
  39. // and requires that we access the internals of the data type:
  40. std::size_t result = CityHash64(reinterpret_cast<const char*>(val.backend().limbs()), val.backend().size() * sizeof(val.backend().limbs()[0]));
  41. // modify the returned hash based on sign:
  42. return val < 0 ? ~result : result;
  43. }
  44. };
  45. //]
  46. void t2()
  47. {
  48. //[hash4
  49. /*`As before insert some values into a container, this time using our custom hasher:*/
  50. std::unordered_set<uint256_t, cityhash> set2;
  51. for(unsigned i = 0; i < 1000; ++i)
  52. set2.insert(ui(mt));
  53. //]
  54. }
  55. int main()
  56. {
  57. t1();
  58. t2();
  59. return 0;
  60. }