point.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2005 Daniel James.
  2. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  3. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  4. // Force use of assert.
  5. #if defined(NDEBUG)
  6. #undef NDEBUG
  7. #endif
  8. #include <boost/container_hash/hash.hpp>
  9. #include <cassert>
  10. // This example illustrates how to use boost::hash_combine to generate a hash
  11. // value from the different members of a class. For full details see the hash
  12. // tutorial.
  13. class point
  14. {
  15. int x;
  16. int y;
  17. public:
  18. point() : x(0), y(0) {}
  19. point(int x, int y) : x(x), y(y) {}
  20. bool operator==(point const& other) const
  21. {
  22. return x == other.x && y == other.y;
  23. }
  24. friend std::size_t hash_value(point const& p)
  25. {
  26. std::size_t seed = 0;
  27. boost::hash_combine(seed, p.x);
  28. boost::hash_combine(seed, p.y);
  29. return seed;
  30. }
  31. };
  32. int main()
  33. {
  34. boost::hash<point> point_hasher;
  35. point p1(0, 0);
  36. point p2(1, 2);
  37. point p3(4, 1);
  38. point p4 = p1;
  39. assert(point_hasher(p1) == point_hasher(p4));
  40. // These tests could legally fail, but if they did it'd be a pretty bad
  41. // hash function.
  42. assert(point_hasher(p1) != point_hasher(p2));
  43. assert(point_hasher(p1) != point_hasher(p3));
  44. return 0;
  45. }