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