3 // Copyright (C) 2005-2013 Free Software Foundation, Inc.
5 // This file is part of the GNU ISO C++ Library. This library is free
6 // software; you can redistribute it and/or modify it under the terms
7 // of the GNU General Public License as published by the Free Software
8 // Foundation; either version 3, or (at your option) any later
11 // This library is distributed in the hope that it will be useful, but
12 // WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this library; see the file COPYING3. If not see
18 // <http://www.gnu.org/licenses/>.
21 // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.
23 // Permission to use, copy, modify, sell, and distribute this software
24 // is hereby granted without fee, provided that the above copyright
25 // notice appears in all copies, and that both that copyright notice
26 // and this permission notice appear in supporting documentation. None
27 // of the above authors, nor IBM Haifa Research Laboratories, make any
28 // representation about the suitability of this software for any
29 // purpose. It is provided "as is" without express or implied
33 * @file tree_join_example.cpp
34 * An example showing how to join splay_tree_map objects.
35 * The code in the example is relevant to red-black trees as well.
39 * This example shows how to join tree based containers, i.e., taking two
40 * objects with non-overlapping sets of keys and combining them into
45 #include <ext/pb_ds/assoc_container.hpp>
46 // For join_error exception.
47 #include <ext/pb_ds/exception.hpp>
52 using namespace __gnu_pbds
;
53 using namespace __gnu_pbds
;
60 // A splay tree table mapping ints to chars.
61 typedef tree
<int, char, less
<int>, splay_tree_tag
> map_t
;
66 // Insert some values into the first table.
67 for (int i0
= 0; i0
< 100; ++i0
)
68 h0
.insert(make_pair(i0
, 'a'));
70 // Insert some values into the second table.
71 for (int i1
= 0; i1
< 100; ++i1
)
72 h1
.insert(make_pair(1000 + i1
, 'b'));
74 // Since all the elements in h0 are smaller than those in h1, it is
75 // possible to join the two tables. This is exception free.
78 // Check that h0 should now contain all entries, and h1 should be empty.
79 assert(h0
.size() == 200);
83 // Two other map_t objects.
91 // Now perform an illegal join.
92 // It is not true that all elements in h2 are smaller than those in
93 // h3, nor is it true that they are all larger. Hence, attempting to
94 // join h2, and h3 should result in an exception.
95 bool exception_thrown
= false;
100 catch (__gnu_pbds::join_error
& )
102 exception_thrown
= true;
104 assert(exception_thrown
);
106 // Since the operation was not performed, the tables should be unaltered.
107 assert(h2
.size() == 2);
108 assert(h3
[2] == 'b');