OSDN Git Service

2012-01-17 Benjamin Kosnik <bkoz@redhat.com>
[pf3gnuchains/gcc-fork.git] / libstdc++-v3 / doc / html / manual / policy_data_structures_design.html
1 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml"><head><title>Design</title><meta name="generator" content="DocBook XSL-NS Stylesheets V1.76.1"/><meta name="keywords" content="&#10;&#9;ISO C++&#10;      , &#10;&#9;policy&#10;      , &#10;&#9;container&#10;      , &#10;&#9;data&#10;      , &#10;&#9;structure&#10;      , &#10;&#9;associated&#10;      , &#10;&#9;tree&#10;      , &#10;&#9;trie&#10;      , &#10;&#9;hash&#10;      , &#10;&#9;metaprogramming&#10;      "/><meta name="keywords" content="&#10;      ISO C++&#10;    , &#10;      library&#10;    "/><meta name="keywords" content="&#10;      ISO C++&#10;    , &#10;      runtime&#10;    , &#10;      library&#10;    "/><link rel="home" href="../index.html" title="The GNU C++ Library"/><link rel="up" href="policy_data_structures.html" title="Chapter 22. Policy-Based Data Structures"/><link rel="prev" href="policy_data_structures_using.html" title="Using"/><link rel="next" href="policy_based_data_structures_test.html" title="Testing"/></head><body><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">Design</th></tr><tr><td align="left"><a accesskey="p" href="policy_data_structures_using.html">Prev</a> </td><th width="60%" align="center">Chapter 22. Policy-Based Data Structures</th><td align="right"> <a accesskey="n" href="policy_based_data_structures_test.html">Next</a></td></tr></table><hr/></div><div class="section" title="Design"><div class="titlepage"><div><div><h2 class="title"><a id="containers.pbds.design"/>Design</h2></div></div></div><p/><div class="section" title="Concepts"><div class="titlepage"><div><div><h3 class="title"><a id="pbds.design.concepts"/>Concepts</h3></div></div></div><div class="section" title="Null Policy Classes"><div class="titlepage"><div><div><h4 class="title"><a id="pbds.design.concepts.null_type"/>Null Policy Classes</h4></div></div></div><p>
4         Associative containers are typically parametrized by various
5         policies. For example, a hash-based associative container is
6         parametrized by a hash-functor, transforming each key into an
7         non-negative numerical type. Each such value is then further mapped
8         into a position within the table. The mapping of a key into a
9         position within the table is therefore a two-step process.
10       </p><p>
11         In some cases, instantiations are redundant. For example, when the
12         keys are integers, it is possible to use a redundant hash policy,
13         which transforms each key into its value.
14       </p><p>
15         In some other cases, these policies are irrelevant.  For example, a
16         hash-based associative container might transform keys into positions
17         within a table by a different method than the two-step method
18         described above. In such a case, the hash functor is simply
19         irrelevant.
20       </p><p>
21         When a policy is either redundant or irrelevant, it can be replaced
22         by <code class="classname">null_type</code>.
23       </p><p>
24         For example, a <span class="emphasis"><em>set</em></span> is an associative
25         container with one of its template parameters (the one for the
26         mapped type) replaced with <code class="classname">null_type</code>. Other
27         places simplifications are made possible with this technique
28         include node updates in tree and trie data structures, and hash
29         and probe functions for hash data structures.
30       </p></div><div class="section" title="Map and Set Semantics"><div class="titlepage"><div><div><h4 class="title"><a id="pbds.design.concepts.associative_semantics"/>Map and Set Semantics</h4></div></div></div><div class="section" title="Distinguishing Between Maps and Sets"><div class="titlepage"><div><div><h5 class="title"><a id="concepts.associative_semantics.set_vs_map"/>
31             Distinguishing Between Maps and Sets
32           </h5></div></div></div><p>
33           Anyone familiar with the standard knows that there are four kinds
34           of associative containers: maps, sets, multimaps, and
35           multisets. The map datatype associates each key to
36           some data.
37         </p><p>
38           Sets are associative containers that simply store keys -
39           they do not map them to anything. In the standard, each map class
40           has a corresponding set class. E.g.,
41           <code class="classname">std::map&lt;int, char&gt;</code> maps each
42           <code class="classname">int</code> to a <code class="classname">char</code>, but
43           <code class="classname">std::set&lt;int, char&gt;</code> simply stores
44           <code class="classname">int</code>s. In this library, however, there are no
45           distinct classes for maps and sets. Instead, an associative
46           container's <code class="classname">Mapped</code> template parameter is a policy: if
47           it is instantiated by <code class="classname">null_type</code>, then it
48           is a "set"; otherwise, it is a "map". E.g.,
49         </p><pre class="programlisting">
50           cc_hash_table&lt;int, char&gt;
51         </pre><p>
52           is a "map" mapping each <span class="type">int</span> value to a <span class="type">
53           char</span>, but
54         </p><pre class="programlisting">
55           cc_hash_table&lt;int, null_type&gt;
56         </pre><p>
57           is a type that uniquely stores <span class="type">int</span> values.
58         </p><p>Once the <code class="classname">Mapped</code> template parameter is instantiated
59         by <code class="classname">null_type</code>, then
60         the "set" acts very similarly to the standard's sets - it does not
61         map each key to a distinct <code class="classname">null_type</code> object. Also,
62         , the container's <span class="type">value_type</span> is essentially
63         its <span class="type">key_type</span> - just as with the standard's sets
64         .</p><p>
65           The standard's multimaps and multisets allow, respectively,
66           non-uniquely mapping keys and non-uniquely storing keys. As
67           discussed, the
68           reasons why this might be necessary are 1) that a key might be
69           decomposed into a primary key and a secondary key, 2) that a
70           key might appear more than once, or 3) any arbitrary
71           combination of 1)s and 2)s. Correspondingly,
72           one should use 1) "maps" mapping primary keys to secondary
73           keys, 2) "maps" mapping keys to size types, or 3) any arbitrary
74           combination of 1)s and 2)s. Thus, for example, an
75           <code class="classname">std::multiset&lt;int&gt;</code> might be used to store
76           multiple instances of integers, but using this library's
77           containers, one might use
78         </p><pre class="programlisting">
79           tree&lt;int, size_t&gt;
80         </pre><p>
81           i.e., a <code class="classname">map</code> of <span class="type">int</span>s to
82           <span class="type">size_t</span>s.
83         </p><p>
84           These "multimaps" and "multisets" might be confusing to
85           anyone familiar with the standard's <code class="classname">std::multimap</code> and
86           <code class="classname">std::multiset</code>, because there is no clear
87           correspondence between the two. For example, in some cases
88           where one uses <code class="classname">std::multiset</code> in the standard, one might use
89           in this library a "multimap" of "multisets" - i.e., a
90           container that maps primary keys each to an associative
91           container that maps each secondary key to the number of times
92           it occurs.
93         </p><p>
94           When one uses a "multimap," one should choose with care the
95           type of container used for secondary keys.
96         </p></div><div class="section" title="Alternatives to std::multiset and std::multimap"><div class="titlepage"><div><div><h5 class="title"><a id="concepts.associative_semantics.multi"/>Alternatives to <code class="classname">std::multiset</code> and <code class="classname">std::multimap</code></h5></div></div></div><p>
97           Brace onself: this library does not contain containers like
98           <code class="classname">std::multimap</code> or
99           <code class="classname">std::multiset</code>. Instead, these data
100           structures can be synthesized via manipulation of the
101           <code class="classname">Mapped</code> template parameter.
102         </p><p>
103           One maps the unique part of a key - the primary key, into an
104           associative-container of the (originally) non-unique parts of
105           the key - the secondary key. A primary associative-container
106           is an associative container of primary keys; a secondary
107           associative-container is an associative container of
108           secondary keys.
109         </p><p>
110           Stepping back a bit, and starting in from the beginning.
111         </p><p>
112           Maps (or sets) allow mapping (or storing) unique-key values.
113           The standard library also supplies associative containers which
114           map (or store) multiple values with equivalent keys:
115           <code class="classname">std::multimap</code>, <code class="classname">std::multiset</code>,
116           <code class="classname">std::tr1::unordered_multimap</code>, and
117           <code class="classname">unordered_multiset</code>. We first discuss how these might
118           be used, then why we think it is best to avoid them.
119         </p><p>
120           Suppose one builds a simple bank-account application that
121           records for each client (identified by an <code class="classname">std::string</code>)
122           and account-id (marked by an <span class="type">unsigned long</span>) -
123           the balance in the account (described by a
124           <span class="type">float</span>). Suppose further that ordering this
125           information is not useful, so a hash-based container is
126           preferable to a tree based container. Then one can use
127         </p><pre class="programlisting">
128           std::tr1::unordered_map&lt;std::pair&lt;std::string, unsigned long&gt;, float, ...&gt;
129         </pre><p>
130           which hashes every combination of client and account-id. This
131           might work well, except for the fact that it is now impossible
132           to efficiently list all of the accounts of a specific client
133           (this would practically require iterating over all
134           entries). Instead, one can use
135         </p><pre class="programlisting">
136           std::tr1::unordered_multimap&lt;std::pair&lt;std::string, unsigned long&gt;, float, ...&gt;
137         </pre><p>
138           which hashes every client, and decides equivalence based on
139           client only. This will ensure that all accounts belonging to a
140           specific user are stored consecutively.
141         </p><p>
142           Also, suppose one wants an integers' priority queue
143           (a container that supports <code class="function">push</code>,
144           <code class="function">pop</code>, and <code class="function">top</code> operations, the last of which
145           returns the largest <span class="type">int</span>) that also supports
146           operations such as <code class="function">find</code> and <code class="function">lower_bound</code>. A
147           reasonable solution is to build an adapter over
148           <code class="classname">std::set&lt;int&gt;</code>. In this adapter,
149           <code class="function">push</code> will just call the tree-based
150           associative container's <code class="function">insert</code> method; <code class="function">pop</code>
151           will call its <code class="function">end</code> method, and use it to return the
152           preceding element (which must be the largest). Then this might
153           work well, except that the container object cannot hold
154           multiple instances of the same integer (<code class="function">push(4)</code>,
155           will be a no-op if <code class="constant">4</code> is already in the
156           container object). If multiple keys are necessary, then one
157           might build the adapter over an
158           <code class="classname">std::multiset&lt;int&gt;</code>.
159         </p><p>
160           The standard library's non-unique-mapping containers are useful
161           when (1) a key can be decomposed in to a primary key and a
162           secondary key, (2) a key is needed multiple times, or (3) any
163           combination of (1) and (2).
164         </p><p>
165           The graphic below shows how the standard library's container
166           design works internally; in this figure nodes shaded equally
167           represent equivalent-key values. Equivalent keys are stored
168           consecutively using the properties of the underlying data
169           structure: binary search trees (label A) store equivalent-key
170           values consecutively (in the sense of an in-order walk)
171           naturally; collision-chaining hash tables (label B) store
172           equivalent-key values in the same bucket, the bucket can be
173           arranged so that equivalent-key values are consecutive.
174         </p><div class="figure"><a id="id519449"/><p class="title"><strong>Figure 22.8. Non-unique Mapping Standard Containers</strong></p><div class="figure-contents"><div class="mediaobject" style="text-align: center"><img src="../images/pbds_embedded_lists_1.png" style="text-align: middle" alt="Non-unique Mapping Standard Containers"/></div></div></div><br class="figure-break"/><p>
175           Put differently, the standards' non-unique mapping
176           associative-containers are associative containers that map
177           primary keys to linked lists that are embedded into the
178           container. The graphic below shows again the two
179           containers from the first graphic above, this time with
180           the embedded linked lists of the grayed nodes marked
181           explicitly.
182         </p><div class="figure"><a id="fig.pbds_embedded_lists_2"/><p class="title"><strong>Figure 22.9. 
183             Effect of embedded lists in
184             <code class="classname">std::multimap</code>
185           </strong></p><div class="figure-contents"><div class="mediaobject" style="text-align: center"><img src="../images/pbds_embedded_lists_2.png" style="text-align: middle" alt="Effect of embedded lists in std::multimap"/></div></div></div><br class="figure-break"/><p>
186           These embedded linked lists have several disadvantages.
187         </p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p>
188               The underlying data structure embeds the linked lists
189               according to its own consideration, which means that the
190               search path for a value might include several different
191               equivalent-key values. For example, the search path for the
192               the black node in either of the first graphic, labels A or B,
193               includes more than a single gray node.
194             </p></li><li class="listitem"><p>
195               The links of the linked lists are the underlying data
196               structures' nodes, which typically are quite structured.  In
197               the case of tree-based containers (the grapic above, label
198               B), each "link" is actually a node with three pointers (one
199               to a parent and two to children), and a
200               relatively-complicated iteration algorithm. The linked
201               lists, therefore, can take up quite a lot of memory, and
202               iterating over all values equal to a given key (through the
203               return value of the standard
204               library's <code class="function">equal_range</code>) can be
205               expensive.
206             </p></li><li class="listitem"><p>
207               The primary key is stored multiply; this uses more memory.
208             </p></li><li class="listitem"><p>
209               Finally, the interface of this design excludes several
210               useful underlying data structures. Of all the unordered
211               self-organizing data structures, practically only
212               collision-chaining hash tables can (efficiently) guarantee
213               that equivalent-key values are stored consecutively.
214             </p></li></ol></div><p>
215           The above reasons hold even when the ratio of secondary keys to
216           primary keys (or average number of identical keys) is small, but
217           when it is large, there are more severe problems:
218         </p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p>
219               The underlying data structures order the links inside each
220               embedded linked-lists according to their internal
221               considerations, which effectively means that each of the
222               links is unordered. Irrespective of the underlying data
223               structure, searching for a specific value can degrade to
224               linear complexity.
225             </p></li><li class="listitem"><p>
226               Similarly to the above point, it is impossible to apply
227               to the secondary keys considerations that apply to primary
228               keys. For example, it is not possible to maintain secondary
229               keys by sorted order.
230             </p></li><li class="listitem"><p>
231               While the interface "understands" that all equivalent-key
232               values constitute a distinct list (through
233               <code class="function">equal_range</code>), the underlying data
234               structure typically does not. This means that operations such
235               as erasing from a tree-based container all values whose keys
236               are equivalent to a a given key can be super-linear in the
237               size of the tree; this is also true also for several other
238               operations that target a specific list.
239             </p></li></ol></div><p>
240           In this library, all associative containers map
241           (or store) unique-key values. One can (1) map primary keys to
242           secondary associative-containers (containers of
243           secondary keys) or non-associative containers (2) map identical
244           keys to a size-type representing the number of times they
245           occur, or (3) any combination of (1) and (2). Instead of
246           allowing multiple equivalent-key values, this library
247           supplies associative containers based on underlying
248           data structures that are suitable as secondary
249           associative-containers.
250         </p><p>
251           In the figure below, labels A and B show the equivalent
252           underlying data structures in this library, as mapped to the
253           first graphic above. Labels A and B, respectively. Each shaded
254           box represents some size-type or secondary
255           associative-container.
256         </p><div class="figure"><a id="id519645"/><p class="title"><strong>Figure 22.10. Non-unique Mapping Containers</strong></p><div class="figure-contents"><div class="mediaobject" style="text-align: center"><img src="../images/pbds_embedded_lists_3.png" style="text-align: middle" alt="Non-unique Mapping Containers"/></div></div></div><br class="figure-break"/><p>
257           In the first example above, then, one would use an associative
258           container mapping each user to an associative container which
259           maps each application id to a start time (see
260           <code class="filename">example/basic_multimap.cc</code>); in the second
261           example, one would use an associative container mapping
262           each <code class="classname">int</code> to some size-type indicating the
263           number of times it logically occurs
264           (see <code class="filename">example/basic_multiset.cc</code>.
265         </p><p>
266           See the discussion in list-based container types for containers
267           especially suited as secondary associative-containers.
268         </p></div></div><div class="section" title="Iterator Semantics"><div class="titlepage"><div><div><h4 class="title"><a id="pbds.design.concepts.iterator_semantics"/>Iterator Semantics</h4></div></div></div><div class="section" title="Point and Range Iterators"><div class="titlepage"><div><div><h5 class="title"><a id="concepts.iterator_semantics.point_and_range"/>Point and Range Iterators</h5></div></div></div><p>
269           Iterator concepts are bifurcated in this design, and are
270           comprised of point-type and range-type iteration.
271         </p><p>
272           A point-type iterator is an iterator that refers to a specific
273           element as returned through an
274           associative-container's <code class="function">find</code> method.
275         </p><p>
276           A range-type iterator is an iterator that is used to go over a
277           sequence of elements, as returned by a container's
278           <code class="function">find</code> method.
279         </p><p>
280           A point-type method is a method that
281           returns a point-type iterator; a range-type method is a method
282           that returns a range-type iterator.
283         </p><p>For most containers, these types are synonymous; for
284         self-organizing containers, such as hash-based containers or
285         priority queues, these are inherently different (in any
286         implementation, including that of C++ standard library
287         components), but in this design, it is made explicit. They are
288         distinct types.
289         </p></div><div class="section" title="Distinguishing Point and Range Iterators"><div class="titlepage"><div><div><h5 class="title"><a id="concepts.iterator_semantics.both"/>Distinguishing Point and Range Iterators</h5></div></div></div><p>When using this library, is necessary to differentiate
290         between two types of methods and iterators: point-type methods and
291         iterators, and range-type methods and iterators. Each associative
292         container's interface includes the methods:</p><pre class="programlisting">
293           point_const_iterator
294           find(const_key_reference r_key) const;
295
296           point_iterator
297           find(const_key_reference r_key);
298
299           std::pair&lt;point_iterator,bool&gt;
300           insert(const_reference r_val);
301         </pre><p>The relationship between these iterator types varies between
302         container types. The figure below
303         shows the most general invariant between point-type and
304         range-type iterators: In <span class="emphasis"><em>A</em></span> <code class="literal">iterator</code>, can
305         always be converted to <code class="literal">point_iterator</code>. In <span class="emphasis"><em>B</em></span>
306         shows invariants for order-preserving containers: point-type
307         iterators are synonymous with range-type iterators.
308         Orthogonally,  <span class="emphasis"><em>C</em></span>shows invariants for "set"
309         containers: iterators are synonymous with const iterators.</p><div class="figure"><a id="id519810"/><p class="title"><strong>Figure 22.11. Point Iterator Hierarchy</strong></p><div class="figure-contents"><div class="mediaobject" style="text-align: center"><img src="../images/pbds_point_iterator_hierarchy.png" style="text-align: middle" alt="Point Iterator Hierarchy"/></div></div></div><br class="figure-break"/><p>Note that point-type iterators in self-organizing containers
310         (hash-based associative containers) lack movement
311         operators, such as <code class="literal">operator++</code> - in fact, this
312         is the reason why this library differentiates from the standard C++ librarys
313         design on this point.</p><p>Typically, one can determine an iterator's movement
314         capabilities using
315         <code class="literal">std::iterator_traits&lt;It&gt;iterator_category</code>,
316         which is a <code class="literal">struct</code> indicating the iterator's
317         movement capabilities. Unfortunately, none of the standard predefined
318         categories reflect a pointer's <span class="emphasis"><em>not</em></span> having any
319         movement capabilities whatsoever. Consequently,
320         <code class="literal">pb_ds</code> adds a type
321         <code class="literal">trivial_iterator_tag</code> (whose name is taken from
322         a concept in C++ standardese, which is the category of iterators
323         with no movement capabilities.) All other standard C++ library
324         tags, such as <code class="literal">forward_iterator_tag</code> retain their
325         common use.</p></div><div class="section" title="Invalidation Guarantees"><div class="titlepage"><div><div><h5 class="title"><a id="pbds.design.concepts.invalidation"/>Invalidation Guarantees</h5></div></div></div><p>
326           If one manipulates a container object, then iterators previously
327           obtained from it can be invalidated. In some cases a
328           previously-obtained iterator cannot be de-referenced; in other cases,
329           the iterator's next or previous element might have changed
330           unpredictably. This corresponds exactly to the question whether a
331           point-type or range-type iterator (see previous concept) is valid or
332           not. In this design, one can query a container (in compile time) about
333           its invalidation guarantees.
334         </p><p>
335           Given three different types of associative containers, a modifying
336           operation (in that example, <code class="function">erase</code>) invalidated
337           iterators in three different ways: the iterator of one container
338           remained completely valid - it could be de-referenced and
339           incremented; the iterator of a different container could not even be
340           de-referenced; the iterator of the third container could be
341           de-referenced, but its "next" iterator changed unpredictably.
342         </p><p>
343           Distinguishing between find and range types allows fine-grained
344           invalidation guarantees, because these questions correspond exactly
345           to the question of whether point-type iterators and range-type
346           iterators are valid. The graphic below shows tags corresponding to
347           different types of invalidation guarantees.
348         </p><div class="figure"><a id="id519922"/><p class="title"><strong>Figure 22.12. Invalidation Guarantee Tags Hierarchy</strong></p><div class="figure-contents"><div class="mediaobject" style="text-align: center"><img src="../images/pbds_invalidation_tag_hierarchy.png" style="text-align: middle" alt="Invalidation Guarantee Tags Hierarchy"/></div></div></div><br class="figure-break"/><div class="itemizedlist"><ul class="itemizedlist"><li class="listitem"><p>
349               <code class="classname">basic_invalidation_guarantee</code>
350               corresponds to a basic guarantee that a point-type iterator,
351               a found pointer, or a found reference, remains valid as long
352               as the container object is not modified.
353             </p></li><li class="listitem"><p>
354               <code class="classname">point_invalidation_guarantee</code>
355               corresponds to a guarantee that a point-type iterator, a
356               found pointer, or a found reference, remains valid even if
357               the container object is modified.
358             </p></li><li class="listitem"><p>
359               <code class="classname">range_invalidation_guarantee</code>
360               corresponds to a guarantee that a range-type iterator remains
361               valid even if the container object is modified.
362             </p></li></ul></div><p>To find the invalidation guarantee of a
363         container, one can use</p><pre class="programlisting">
364           typename container_traits&lt;Cntnr&gt;::invalidation_guarantee
365         </pre><p>Note that this hierarchy corresponds to the logic it
366         represents: if a container has range-invalidation guarantees,
367         then it must also have find invalidation guarantees;
368         correspondingly, its invalidation guarantee (in this case
369         <code class="classname">range_invalidation_guarantee</code>)
370         can be cast to its base class (in this case <code class="classname">point_invalidation_guarantee</code>).
371         This means that this this hierarchy can be used easily using
372         standard metaprogramming techniques, by specializing on the
373         type of <code class="literal">invalidation_guarantee</code>.</p><p>
374           These types of problems were addressed, in a more general
375           setting, in <a class="xref" href="policy_data_structures.html#biblio.meyers96more" title="More Effective C++: 35 New Ways to Improve Your Programs and Designs">[biblio.meyers96more]</a> - Item 2. In
376           our opinion, an invalidation-guarantee hierarchy would solve
377           these problems in all container types - not just associative
378           containers.
379         </p></div></div><div class="section" title="Genericity"><div class="titlepage"><div><div><h4 class="title"><a id="pbds.design.concepts.genericity"/>Genericity</h4></div></div></div><p>
380         The design attempts to address the following problem of
381         data-structure genericity. When writing a function manipulating
382         a generic container object, what is the behavior of the object?
383         Suppose one writes
384       </p><pre class="programlisting">
385         template&lt;typename Cntnr&gt;
386         void
387         some_op_sequence(Cntnr &amp;r_container)
388         {
389         ...
390         }
391       </pre><p>
392         then one needs to address the following questions in the body
393         of <code class="function">some_op_sequence</code>:
394       </p><div class="itemizedlist"><ul class="itemizedlist"><li class="listitem"><p>
395             Which types and methods does <code class="literal">Cntnr</code> support?
396             Containers based on hash tables can be queries for the
397             hash-functor type and object; this is meaningless for tree-based
398             containers. Containers based on trees can be split, joined, or
399             can erase iterators and return the following iterator; this
400             cannot be done by hash-based containers.
401           </p></li><li class="listitem"><p>
402             What are the exception and invalidation guarantees
403             of <code class="literal">Cntnr</code>? A container based on a probing
404             hash-table invalidates all iterators when it is modified; this
405             is not the case for containers based on node-based
406             trees. Containers based on a node-based tree can be split or
407             joined without exceptions; this is not the case for containers
408             based on vector-based trees.
409           </p></li><li class="listitem"><p>
410             How does the container maintain its elements? Tree-based and
411             Trie-based containers store elements by key order; others,
412             typically, do not. A container based on a splay trees or lists
413             with update policies "cache" "frequently accessed" elements;
414             containers based on most other underlying data structures do
415             not.
416           </p></li><li class="listitem"><p>
417             How does one query a container about characteristics and
418             capabilities? What is the relationship between two different
419             data structures, if anything?
420           </p></li></ul></div><p>The remainder of this section explains these issues in
421       detail.</p><div class="section" title="Tag"><div class="titlepage"><div><div><h5 class="title"><a id="concepts.genericity.tag"/>Tag</h5></div></div></div><p>
422           Tags are very useful for manipulating generic types. For example, if
423           <code class="literal">It</code> is an iterator class, then <code class="literal">typename
424           It::iterator_category</code> or <code class="literal">typename
425           std::iterator_traits&lt;It&gt;::iterator_category</code> will
426           yield its category, and <code class="literal">typename
427           std::iterator_traits&lt;It&gt;::value_type</code> will yield its
428           value type.
429         </p><p>
430           This library contains a container tag hierarchy corresponding to the
431           diagram below.
432         </p><div class="figure"><a id="id520174"/><p class="title"><strong>Figure 22.13. Container Tag Hierarchy</strong></p><div class="figure-contents"><div class="mediaobject" style="text-align: center"><img src="../images/pbds_container_tag_hierarchy.png" style="text-align: middle" alt="Container Tag Hierarchy"/></div></div></div><br class="figure-break"/><p>
433           Given any container <span class="type">Cntnr</span>, the tag of
434           the underlying data structure can be found via <code class="literal">typename
435           Cntnr::container_category</code>.
436         </p></div><div class="section" title="Traits"><div class="titlepage"><div><div><h5 class="title"><a id="concepts.genericity.traits"/>Traits</h5></div></div></div><p/><p>Additionally, a traits mechanism can be used to query a
437         container type for its attributes. Given any container
438         <code class="literal">Cntnr</code>, then <code class="literal">&lt;Cntnr&gt;</code>
439         is a traits class identifying the properties of the
440         container.</p><p>To find if a container can throw when a key is erased (which
441         is true for vector-based trees, for example), one can
442         use
443         </p><pre class="programlisting">container_traits&lt;Cntnr&gt;::erase_can_throw</pre><p>
444           Some of the definitions in <code class="classname">container_traits</code>
445           are dependent on other
446           definitions. If <code class="classname">container_traits&lt;Cntnr&gt;::order_preserving</code>
447           is <code class="constant">true</code> (which is the case for containers
448           based on trees and tries), then the container can be split or
449           joined; in this
450           case, <code class="classname">container_traits&lt;Cntnr&gt;::split_join_can_throw</code>
451           indicates whether splits or joins can throw exceptions (which is
452           true for vector-based trees);
453           otherwise <code class="classname">container_traits&lt;Cntnr&gt;::split_join_can_throw</code>
454           will yield a compilation error. (This is somewhat similar to a
455           compile-time version of the COM model).
456         </p></div></div></div><div class="section" title="By Container"><div class="titlepage"><div><div><h3 class="title"><a id="pbds.design.container"/>By Container</h3></div></div></div><div class="section" title="hash"><div class="titlepage"><div><div><h4 class="title"><a id="pbds.design.container.hash"/>hash</h4></div></div></div><div class="section" title="Interface"><div class="titlepage"><div><div><h5 class="title"><a id="container.hash.interface"/>Interface</h5></div></div></div><p>
457           The collision-chaining hash-based container has the
458         following declaration.</p><pre class="programlisting">
459           template&lt;
460           typename Key,
461           typename Mapped,
462           typename Hash_Fn = std::hash&lt;Key&gt;,
463           typename Eq_Fn = std::equal_to&lt;Key&gt;,
464           typename Comb_Hash_Fn =  direct_mask_range_hashing&lt;&gt;
465           typename Resize_Policy = default explained below.
466           bool Store_Hash = false,
467           typename Allocator = std::allocator&lt;char&gt; &gt;
468           class cc_hash_table;
469         </pre><p>The parameters have the following meaning:</p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p><code class="classname">Key</code> is the key type.</p></li><li class="listitem"><p><code class="classname">Mapped</code> is the mapped-policy.</p></li><li class="listitem"><p><code class="classname">Hash_Fn</code> is a key hashing functor.</p></li><li class="listitem"><p><code class="classname">Eq_Fn</code> is a key equivalence functor.</p></li><li class="listitem"><p><code class="classname">Comb_Hash_Fn</code> is a range-hashing_functor;
470           it describes how to translate hash values into positions
471           within the table. </p></li><li class="listitem"><p><code class="classname">Resize_Policy</code> describes how a container object
472           should change its internal size. </p></li><li class="listitem"><p><code class="classname">Store_Hash</code> indicates whether the hash value
473           should be stored with each entry. </p></li><li class="listitem"><p><code class="classname">Allocator</code> is an allocator
474           type.</p></li></ol></div><p>The probing hash-based container has the following
475         declaration.</p><pre class="programlisting">
476           template&lt;
477           typename Key,
478           typename Mapped,
479           typename Hash_Fn = std::hash&lt;Key&gt;,
480           typename Eq_Fn = std::equal_to&lt;Key&gt;,
481           typename Comb_Probe_Fn = direct_mask_range_hashing&lt;&gt;
482           typename Probe_Fn = default explained below.
483           typename Resize_Policy = default explained below.
484           bool Store_Hash = false,
485           typename Allocator =  std::allocator&lt;char&gt; &gt;
486           class gp_hash_table;
487         </pre><p>The parameters are identical to those of the
488         collision-chaining container, except for the following.</p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p><code class="classname">Comb_Probe_Fn</code> describes how to transform a probe
489           sequence into a sequence of positions within the table.</p></li><li class="listitem"><p><code class="classname">Probe_Fn</code> describes a probe sequence policy.</p></li></ol></div><p>Some of the default template values depend on the values of
490         other parameters, and are explained below.</p></div><div class="section" title="Details"><div class="titlepage"><div><div><h5 class="title"><a id="container.hash.details"/>Details</h5></div></div></div><div class="section" title="Hash Policies"><div class="titlepage"><div><div><h6 class="title"><a id="container.hash.details.hash_policies"/>Hash Policies</h6></div></div></div><div class="section" title="General"><div class="titlepage"><div><div><h6 class="title"><a id="details.hash_policies.general"/>General</h6></div></div></div><p>Following is an explanation of some functions which hashing
491             involves. The graphic below illustrates the discussion.</p><div class="figure"><a id="id520506"/><p class="title"><strong>Figure 22.14. Hash functions, ranged-hash functions, and
492               range-hashing functions</strong></p><div class="figure-contents"><div class="mediaobject" style="text-align: center"><img src="../images/pbds_hash_ranged_hash_range_hashing_fns.png" style="text-align: middle" alt="Hash functions, ranged-hash functions, and range-hashing functions"/></div></div></div><br class="figure-break"/><p>Let U be a domain (e.g., the integers, or the
493             strings of 3 characters). A hash-table algorithm needs to map
494             elements of U "uniformly" into the range [0,..., m -
495             1] (where m is a non-negative integral value, and
496             is, in general, time varying). I.e., the algorithm needs
497             a ranged-hash function</p><p>
498               f : U × Z<sub>+</sub> → Z<sub>+</sub>
499             </p><p>such that for any u in U ,</p><p>0 ≤ f(u, m) ≤ m - 1</p><p>and which has "good uniformity" properties (say
500             <a class="xref" href="policy_data_structures.html#biblio.knuth98sorting" title="The Art of Computer Programming - Sorting and Searching">[biblio.knuth98sorting]</a>.)
501             One
502             common solution is to use the composition of the hash
503             function</p><p>h : U → Z<sub>+</sub> ,</p><p>which maps elements of U into the non-negative
504             integrals, and</p><p>g : Z<sub>+</sub> × Z<sub>+</sub> →
505             Z<sub>+</sub>,</p><p>which maps a non-negative hash value, and a non-negative
506             range upper-bound into a non-negative integral in the range
507             between 0 (inclusive) and the range upper bound (exclusive),
508             i.e., for any r in Z<sub>+</sub>,</p><p>0 ≤ g(r, m) ≤ m - 1</p><p>The resulting ranged-hash function, is</p><div class="equation"><a id="id520621"/><p class="title"><strong>Equation 22.1. Ranged Hash Function</strong></p><div class="equation-contents"><span class="mathphrase">
509                 f(u , m) = g(h(u), m)
510               </span></div></div><br class="equation-break"/><p>From the above, it is obvious that given g and
511             h, f can always be composed (however the converse
512             is not true). The standard's hash-based containers allow specifying
513             a hash function, and use a hard-wired range-hashing function;
514             the ranged-hash function is implicitly composed.</p><p>The above describes the case where a key is to be mapped
515             into a single position within a hash table, e.g.,
516             in a collision-chaining table. In other cases, a key is to be
517             mapped into a sequence of positions within a table,
518             e.g., in a probing table. Similar terms apply in this
519             case: the table requires a ranged probe function,
520             mapping a key into a sequence of positions withing the table.
521             This is typically achieved by composing a hash function
522             mapping the key into a non-negative integral type, a
523             probe function transforming the hash value into a
524             sequence of hash values, and a range-hashing function
525             transforming the sequence of hash values into a sequence of
526             positions.</p></div><div class="section" title="Range Hashing"><div class="titlepage"><div><div><h6 class="title"><a id="details.hash_policies.range"/>Range Hashing</h6></div></div></div><p>Some common choices for range-hashing functions are the
527             division, multiplication, and middle-square methods (<a class="xref" href="policy_data_structures.html#biblio.knuth98sorting" title="The Art of Computer Programming - Sorting and Searching">[biblio.knuth98sorting]</a>), defined
528             as</p><div class="equation"><a id="id520670"/><p class="title"><strong>Equation 22.2. Range-Hashing, Division Method</strong></p><div class="equation-contents"><span class="mathphrase">
529                 g(r, m) = r mod m
530               </span></div></div><br class="equation-break"/><p>g(r, m) = ⌈ u/v ( a r mod v ) ⌉</p><p>and</p><p>g(r, m) = ⌈ u/v ( r<sup>2</sup> mod v ) ⌉</p><p>respectively, for some positive integrals u and
531             v (typically powers of 2), and some a. Each of
532             these range-hashing functions works best for some different
533             setting.</p><p>The division method (see above) is a
534             very common choice. However, even this single method can be
535             implemented in two very different ways. It is possible to
536             implement using the low
537             level % (modulo) operation (for any m), or the
538             low level &amp; (bit-mask) operation (for the case where
539             m is a power of 2), i.e.,</p><div class="equation"><a id="id520708"/><p class="title"><strong>Equation 22.3. Division via Prime Modulo</strong></p><div class="equation-contents"><span class="mathphrase">
540                 g(r, m) = r % m
541               </span></div></div><br class="equation-break"/><p>and</p><div class="equation"><a id="id520723"/><p class="title"><strong>Equation 22.4. Division via Bit Mask</strong></p><div class="equation-contents"><span class="mathphrase">
542                 g(r, m) = r &amp; m - 1, (with m =
543                 2<sup>k</sup> for some k)
544               </span></div></div><br class="equation-break"/><p>respectively.</p><p>The % (modulo) implementation has the advantage that for
545             m a prime far from a power of 2, g(r, m) is
546             affected by all the bits of r (minimizing the chance of
547             collision). It has the disadvantage of using the costly modulo
548             operation. This method is hard-wired into SGI's implementation
549             .</p><p>The &amp; (bit-mask) implementation has the advantage of
550             relying on the fast bit-wise and operation. It has the
551             disadvantage that for g(r, m) is affected only by the
552             low order bits of r. This method is hard-wired into
553             Dinkumware's implementation.</p></div><div class="section" title="Ranged Hash"><div class="titlepage"><div><div><h6 class="title"><a id="details.hash_policies.ranged"/>Ranged Hash</h6></div></div></div><p>In cases it is beneficial to allow the
554             client to directly specify a ranged-hash hash function. It is
555             true, that the writer of the ranged-hash function cannot rely
556             on the values of m having specific numerical properties
557             suitable for hashing (in the sense used in <a class="xref" href="policy_data_structures.html#biblio.knuth98sorting" title="The Art of Computer Programming - Sorting and Searching">[biblio.knuth98sorting]</a>), since
558             the values of m are determined by a resize policy with
559             possibly orthogonal considerations.</p><p>There are two cases where a ranged-hash function can be
560             superior. The firs is when using perfect hashing: the
561             second is when the values of m can be used to estimate
562             the "general" number of distinct values required. This is
563             described in the following.</p><p>Let</p><p>
564               s = [ s<sub>0</sub>,..., s<sub>t - 1</sub>]
565             </p><p>be a string of t characters, each of which is from
566             domain S. Consider the following ranged-hash
567             function:</p><div class="equation"><a id="id520803"/><p class="title"><strong>Equation 22.5. 
568                 A Standard String Hash Function
569               </strong></p><div class="equation-contents"><span class="mathphrase">
570                 f<sub>1</sub>(s, m) = ∑ <sub>i =
571                 0</sub><sup>t - 1</sup> s<sub>i</sub> a<sup>i</sup> mod m
572               </span></div></div><br class="equation-break"/><p>where a is some non-negative integral value. This is
573             the standard string-hashing function used in SGI's
574             implementation (with a = 5). Its advantage is that
575             it takes into account all of the characters of the string.</p><p>Now assume that s is the string representation of a
576             of a long DNA sequence (and so S = {'A', 'C', 'G',
577             'T'}). In this case, scanning the entire string might be
578             prohibitively expensive. A possible alternative might be to use
579             only the first k characters of the string, where</p><p>|S|<sup>k</sup> ≥ m ,</p><p>i.e., using the hash function</p><div class="equation"><a id="id520854"/><p class="title"><strong>Equation 22.6. 
580                 Only k String DNA Hash
581               </strong></p><div class="equation-contents"><span class="mathphrase">
582                 f<sub>2</sub>(s, m) = ∑ <sub>i
583                 = 0</sub><sup>k - 1</sup> s<sub>i</sub> a<sup>i</sup> mod m 
584               </span></div></div><br class="equation-break"/><p>requiring scanning over only</p><p>k = log<sub>4</sub>( m )</p><p>characters.</p><p>Other more elaborate hash-functions might scan k
585             characters starting at a random position (determined at each
586             resize), or scanning k random positions (determined at
587             each resize), i.e., using</p><p>f<sub>3</sub>(s, m) = ∑ <sub>i =
588             r</sub>0<sup>r<sub>0</sub> + k - 1</sup> s<sub>i</sub>
589             a<sup>i</sup> mod m ,</p><p>or</p><p>f<sub>4</sub>(s, m) = ∑ <sub>i = 0</sub><sup>k -
590             1</sup> s<sub>r</sub>i a<sup>r<sub>i</sub></sup> mod
591             m ,</p><p>respectively, for r<sub>0</sub>,..., r<sub>k-1</sub>
592             each in the (inclusive) range [0,...,t-1].</p><p>It should be noted that the above functions cannot be
593             decomposed as per a ranged hash composed of hash and range hashing.</p></div><div class="section" title="Implementation"><div class="titlepage"><div><div><h6 class="title"><a id="details.hash_policies.implementation"/>Implementation</h6></div></div></div><p>This sub-subsection describes the implementation of
594             the above in this library. It first explains range-hashing
595             functions in collision-chaining tables, then ranged-hash
596             functions in collision-chaining tables, then probing-based
597             tables, and finally lists the relevant classes in this
598             library.</p><div class="section" title="Range-Hashing and Ranged-Hashes in Collision-Chaining Tables"><div class="titlepage"><div><div><h6 class="title"><a id="hash_policies.implementation.collision-chaining"/>
599                 Range-Hashing and Ranged-Hashes in Collision-Chaining Tables
600               </h6></div></div></div><p><code class="classname">cc_hash_table</code> is
601               parametrized by <code class="classname">Hash_Fn</code> and <code class="classname">Comb_Hash_Fn</code>, a
602               hash functor and a combining hash functor, respectively.</p><p>In general, <code class="classname">Comb_Hash_Fn</code> is considered a
603               range-hashing functor. <code class="classname">cc_hash_table</code>
604               synthesizes a ranged-hash function from <code class="classname">Hash_Fn</code> and
605               <code class="classname">Comb_Hash_Fn</code>. The figure below shows an <code class="classname">insert</code> sequence
606               diagram for this case. The user inserts an element (point A),
607               the container transforms the key into a non-negative integral
608               using the hash functor (points B and C), and transforms the
609               result into a position using the combining functor (points D
610               and E).</p><div class="figure"><a id="id521043"/><p class="title"><strong>Figure 22.15. Insert hash sequence diagram</strong></p><div class="figure-contents"><div class="mediaobject" style="text-align: center"><img src="../images/pbds_hash_range_hashing_seq_diagram.png" style="text-align: middle" alt="Insert hash sequence diagram"/></div></div></div><br class="figure-break"/><p>If <code class="classname">cc_hash_table</code>'s
611               hash-functor, <code class="classname">Hash_Fn</code> is instantiated by <code class="classname">null_type</code> , then <code class="classname">Comb_Hash_Fn</code> is taken to be
612               a ranged-hash function. The graphic below shows an <code class="function">insert</code> sequence
613               diagram. The user inserts an element (point A), the container
614               transforms the key into a position using the combining functor
615               (points B and C).</p><div class="figure"><a id="id521102"/><p class="title"><strong>Figure 22.16. Insert hash sequence diagram with a null policy</strong></p><div class="figure-contents"><div class="mediaobject" style="text-align: center"><img src="../images/pbds_hash_range_hashing_seq_diagram2.png" style="text-align: middle" alt="Insert hash sequence diagram with a null policy"/></div></div></div><br class="figure-break"/></div><div class="section" title="Probing tables"><div class="titlepage"><div><div><h6 class="title"><a id="hash_policies.implementation.probe"/>
616                 Probing tables
617               </h6></div></div></div><p><code class="classname">gp_hash_table</code> is parametrized by
618               <code class="classname">Hash_Fn</code>, <code class="classname">Probe_Fn</code>,
619               and <code class="classname">Comb_Probe_Fn</code>. As before, if
620               <code class="classname">Hash_Fn</code> and <code class="classname">Probe_Fn</code>
621               are both <code class="classname">null_type</code>, then
622               <code class="classname">Comb_Probe_Fn</code> is a ranged-probe
623               functor. Otherwise, <code class="classname">Hash_Fn</code> is a hash
624               functor, <code class="classname">Probe_Fn</code> is a functor for offsets
625               from a hash value, and <code class="classname">Comb_Probe_Fn</code>
626               transforms a probe sequence into a sequence of positions within
627               the table.</p></div><div class="section" title="Pre-Defined Policies"><div class="titlepage"><div><div><h6 class="title"><a id="hash_policies.implementation.predefined"/>
628                 Pre-Defined Policies
629               </h6></div></div></div><p>This library contains some pre-defined classes
630               implementing range-hashing and probing functions:</p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p><code class="classname">direct_mask_range_hashing</code>
631                 and <code class="classname">direct_mod_range_hashing</code>
632                 are range-hashing functions based on a bit-mask and a modulo
633                 operation, respectively.</p></li><li class="listitem"><p><code class="classname">linear_probe_fn</code>, and
634                 <code class="classname">quadratic_probe_fn</code> are
635                 a linear probe and a quadratic probe function,
636                 respectively.</p></li></ol></div><p>
637                 The graphic below shows the relationships.
638               </p><div class="figure"><a id="id521241"/><p class="title"><strong>Figure 22.17. Hash policy class diagram</strong></p><div class="figure-contents"><div class="mediaobject" style="text-align: center"><img src="../images/pbds_hash_policy_cd.png" style="text-align: middle" alt="Hash policy class diagram"/></div></div></div><br class="figure-break"/></div></div></div><div class="section" title="Resize Policies"><div class="titlepage"><div><div><h6 class="title"><a id="container.hash.details.resize_policies"/>Resize Policies</h6></div></div></div><div class="section" title="General"><div class="titlepage"><div><div><h6 class="title"><a id="resize_policies.general"/>General</h6></div></div></div><p>Hash-tables, as opposed to trees, do not naturally grow or
639             shrink. It is necessary to specify policies to determine how
640             and when a hash table should change its size. Usually, resize
641             policies can be decomposed into orthogonal policies:</p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p>A size policy indicating how a hash table
642               should grow (e.g., it should multiply by powers of
643               2).</p></li><li class="listitem"><p>A trigger policy indicating when a hash
644               table should grow (e.g., a load factor is
645               exceeded).</p></li></ol></div></div><div class="section" title="Size Policies"><div class="titlepage"><div><div><h6 class="title"><a id="resize_policies.size"/>Size Policies</h6></div></div></div><p>Size policies determine how a hash table changes size. These
646             policies are simple, and there are relatively few sensible
647             options. An exponential-size policy (with the initial size and
648             growth factors both powers of 2) works well with a mask-based
649             range-hashing function, and is the
650             hard-wired policy used by Dinkumware. A
651             prime-list based policy works well with a modulo-prime range
652             hashing function and is the hard-wired policy used by SGI's
653             implementation.</p></div><div class="section" title="Trigger Policies"><div class="titlepage"><div><div><h6 class="title"><a id="resize_policies.trigger"/>Trigger Policies</h6></div></div></div><p>Trigger policies determine when a hash table changes size.
654             Following is a description of two policies: load-check
655             policies, and collision-check policies.</p><p>Load-check policies are straightforward. The user specifies
656             two factors, Α<sub>min</sub> and
657             Α<sub>max</sub>, and the hash table maintains the
658             invariant that</p><p>Α<sub>min</sub> ≤ (number of
659             stored elements) / (hash-table size) ≤
660             Α<sub>max</sub><em><span class="remark">load factor min max</span></em></p><p>Collision-check policies work in the opposite direction of
661             load-check policies. They focus on keeping the number of
662             collisions moderate and hoping that the size of the table will
663             not grow very large, instead of keeping a moderate load-factor
664             and hoping that the number of collisions will be small. A
665             maximal collision-check policy resizes when the longest
666             probe-sequence grows too large.</p><p>Consider the graphic below. Let the size of the hash table
667             be denoted by m, the length of a probe sequence be denoted by k,
668             and some load factor be denoted by Α. We would like to
669             calculate the minimal length of k, such that if there were Α
670             m elements in the hash table, a probe sequence of length k would
671             be found with probability at most 1/m.</p><div class="figure"><a id="id521400"/><p class="title"><strong>Figure 22.18. Balls and bins</strong></p><div class="figure-contents"><div class="mediaobject" style="text-align: center"><img src="../images/pbds_balls_and_bins.png" style="text-align: middle" alt="Balls and bins"/></div></div></div><br class="figure-break"/><p>Denote the probability that a probe sequence of length
672             k appears in bin i by p<sub>i</sub>, the
673             length of the probe sequence of bin i by
674             l<sub>i</sub>, and assume uniform distribution. Then</p><div class="equation"><a id="id521446"/><p class="title"><strong>Equation 22.7. 
675                 Probability of Probe Sequence of Length k
676               </strong></p><div class="equation-contents"><span class="mathphrase">
677                 p<sub>1</sub> = 
678               </span></div></div><br class="equation-break"/><p>P(l<sub>1</sub> ≥ k) =</p><p>
679               P(l<sub>1</sub> ≥ α ( 1 + k / α - 1) ≤ (a)
680             </p><p>
681               e ^ ( - ( α ( k / α - 1 )<sup>2</sup> ) /2)
682             </p><p>where (a) follows from the Chernoff bound (<a class="xref" href="policy_data_structures.html#biblio.motwani95random" title="Randomized Algorithms">[biblio.motwani95random]</a>). To
683             calculate the probability that some bin contains a probe
684             sequence greater than k, we note that the
685             l<sub>i</sub> are negatively-dependent
686             (<a class="xref" href="policy_data_structures.html#biblio.dubhashi98neg" title="Balls and bins: A study in negative dependence">[biblio.dubhashi98neg]</a>)
687             . Let
688             I(.) denote the indicator function. Then</p><div class="equation"><a id="id521502"/><p class="title"><strong>Equation 22.8. 
689                 Probability Probe Sequence in Some Bin
690               </strong></p><div class="equation-contents"><span class="mathphrase">
691                 P( exists<sub>i</sub> l<sub>i</sub> ≥ k ) = 
692               </span></div></div><br class="equation-break"/><p>P ( ∑ <sub>i = 1</sub><sup>m</sup>
693             I(l<sub>i</sub> ≥ k) ≥ 1 ) =</p><p>P ( ∑ <sub>i = 1</sub><sup>m</sup> I (
694             l<sub>i</sub> ≥ k ) ≥ m p<sub>1</sub> ( 1 + 1 / (m
695             p<sub>1</sub>) - 1 ) ) ≤ (a)</p><p>e ^ ( ( - m p<sub>1</sub> ( 1 / (m p<sub>1</sub>)
696             - 1 ) <sup>2</sup> ) / 2 ) ,</p><p>where (a) follows from the fact that the Chernoff bound can
697             be applied to negatively-dependent variables (<a class="xref" href="policy_data_structures.html#biblio.dubhashi98neg" title="Balls and bins: A study in negative dependence">[biblio.dubhashi98neg]</a>). Inserting the first probability
698             equation into the second one, and equating with 1/m, we
699             obtain</p><p>k ~ √ ( 2 α ln 2 m ln(m) )
700             ) .</p></div><div class="section" title="Implementation"><div class="titlepage"><div><div><h6 class="title"><a id="resize_policies.impl"/>Implementation</h6></div></div></div><p>This sub-subsection describes the implementation of the
701             above in this library. It first describes resize policies and
702             their decomposition into trigger and size policies, then
703             describes pre-defined classes, and finally discusses controlled
704             access the policies' internals.</p><div class="section" title="Decomposition"><div class="titlepage"><div><div><h6 class="title"><a id="resize_policies.impl.decomposition"/>Decomposition</h6></div></div></div><p>Each hash-based container is parametrized by a
705               <code class="classname">Resize_Policy</code> parameter; the container derives
706               <code class="classname">public</code>ly from <code class="classname">Resize_Policy</code>. For
707               example:</p><pre class="programlisting">
708                 cc_hash_table&lt;typename Key,
709                 typename Mapped,
710                 ...
711                 typename Resize_Policy
712                 ...&gt; : public Resize_Policy
713               </pre><p>As a container object is modified, it continuously notifies
714               its <code class="classname">Resize_Policy</code> base of internal changes
715               (e.g., collisions encountered and elements being
716               inserted). It queries its <code class="classname">Resize_Policy</code> base whether
717               it needs to be resized, and if so, to what size.</p><p>The graphic below shows a (possible) sequence diagram
718               of an insert operation. The user inserts an element; the hash
719               table notifies its resize policy that a search has started
720               (point A); in this case, a single collision is encountered -
721               the table notifies its resize policy of this (point B); the
722               container finally notifies its resize policy that the search
723               has ended (point C); it then queries its resize policy whether
724               a resize is needed, and if so, what is the new size (points D
725               to G); following the resize, it notifies the policy that a
726               resize has completed (point H); finally, the element is
727               inserted, and the policy notified (point I).</p><div class="figure"><a id="id521656"/><p class="title"><strong>Figure 22.19. Insert resize sequence diagram</strong></p><div class="figure-contents"><div class="mediaobject" style="text-align: center"><img src="../images/pbds_insert_resize_sequence_diagram1.png" style="text-align: middle" alt="Insert resize sequence diagram"/></div></div></div><br class="figure-break"/><p>In practice, a resize policy can be usually orthogonally
728               decomposed to a size policy and a trigger policy. Consequently,
729               the library contains a single class for instantiating a resize
730               policy: <code class="classname">hash_standard_resize_policy</code>
731               is parametrized by <code class="classname">Size_Policy</code> and
732               <code class="classname">Trigger_Policy</code>, derives <code class="classname">public</code>ly from
733               both, and acts as a standard delegate (<a class="xref" href="policy_data_structures.html#biblio.gof" title="Design Patterns - Elements of Reusable Object-Oriented Software">[biblio.gof]</a>)
734               to these policies.</p><p>The two graphics immediately below show sequence diagrams
735               illustrating the interaction between the standard resize policy
736               and its trigger and size policies, respectively.</p><div class="figure"><a id="id521721"/><p class="title"><strong>Figure 22.20. Standard resize policy trigger sequence
737                 diagram</strong></p><div class="figure-contents"><div class="mediaobject" style="text-align: center"><img src="../images/pbds_insert_resize_sequence_diagram2.png" style="text-align: middle" alt="Standard resize policy trigger sequence diagram"/></div></div></div><br class="figure-break"/><div class="figure"><a id="id521756"/><p class="title"><strong>Figure 22.21. Standard resize policy size sequence
738                 diagram</strong></p><div class="figure-contents"><div class="mediaobject" style="text-align: center"><img src="../images/pbds_insert_resize_sequence_diagram3.png" style="text-align: middle" alt="Standard resize policy size sequence diagram"/></div></div></div><br class="figure-break"/></div><div class="section" title="Predefined Policies"><div class="titlepage"><div><div><h6 class="title"><a id="resize_policies.impl.predefined"/>Predefined Policies</h6></div></div></div><p>The library includes the following
739               instantiations of size and trigger policies:</p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p><code class="classname">hash_load_check_resize_trigger</code>
740                 implements a load check trigger policy.</p></li><li class="listitem"><p><code class="classname">cc_hash_max_collision_check_resize_trigger</code>
741                 implements a collision check trigger policy.</p></li><li class="listitem"><p><code class="classname">hash_exponential_size_policy</code>
742                 implements an exponential-size policy (which should be used
743                 with mask range hashing).</p></li><li class="listitem"><p><code class="classname">hash_prime_size_policy</code>
744                 implementing a size policy based on a sequence of primes
745                 (which should
746                 be used with mod range hashing</p></li></ol></div><p>The graphic below gives an overall picture of the resize-related
747               classes. <code class="classname">basic_hash_table</code>
748               is parametrized by <code class="classname">Resize_Policy</code>, which it subclasses
749               publicly. This class is currently instantiated only by <code class="classname">hash_standard_resize_policy</code>. 
750               <code class="classname">hash_standard_resize_policy</code>
751               itself is parametrized by <code class="classname">Trigger_Policy</code> and
752               <code class="classname">Size_Policy</code>. Currently, <code class="classname">Trigger_Policy</code> is
753               instantiated by <code class="classname">hash_load_check_resize_trigger</code>,
754               or <code class="classname">cc_hash_max_collision_check_resize_trigger</code>;
755               <code class="classname">Size_Policy</code> is instantiated by <code class="classname">hash_exponential_size_policy</code>,
756               or <code class="classname">hash_prime_size_policy</code>.</p></div><div class="section" title="Controling Access to Internals"><div class="titlepage"><div><div><h6 class="title"><a id="resize_policies.impl.internals"/>Controling Access to Internals</h6></div></div></div><p>There are cases where (controlled) access to resize
757               policies' internals is beneficial. E.g., it is sometimes
758               useful to query a hash-table for the table's actual size (as
759               opposed to its <code class="function">size()</code> - the number of values it
760               currently holds); it is sometimes useful to set a table's
761               initial size, externally resize it, or change load factors.</p><p>Clearly, supporting such methods both decreases the
762               encapsulation of hash-based containers, and increases the
763               diversity between different associative-containers' interfaces.
764               Conversely, omitting such methods can decrease containers'
765               flexibility.</p><p>In order to avoid, to the extent possible, the above
766               conflict, the hash-based containers themselves do not address
767               any of these questions; this is deferred to the resize policies,
768               which are easier to change or replace. Thus, for example,
769               neither <code class="classname">cc_hash_table</code> nor
770               <code class="classname">gp_hash_table</code>
771               contain methods for querying the actual size of the table; this
772               is deferred to <code class="classname">hash_standard_resize_policy</code>.</p><p>Furthermore, the policies themselves are parametrized by
773               template arguments that determine the methods they support
774               (
775               <a class="xref" href="policy_data_structures.html#biblio.alexandrescu01modern" title="Modern C++ Design: Generic Programming and Design Patterns Applied">[biblio.alexandrescu01modern]</a>
776               shows techniques for doing so). <code class="classname">hash_standard_resize_policy</code>
777               is parametrized by <code class="classname">External_Size_Access</code> that
778               determines whether it supports methods for querying the actual
779               size of the table or resizing it. <code class="classname">hash_load_check_resize_trigger</code>
780               is parametrized by <code class="classname">External_Load_Access</code> that
781               determines whether it supports methods for querying or
782               modifying the loads. <code class="classname">cc_hash_max_collision_check_resize_trigger</code>
783               is parametrized by <code class="classname">External_Load_Access</code> that
784               determines whether it supports methods for querying the
785               load.</p><p>Some operations, for example, resizing a container at
786               run time, or changing the load factors of a load-check trigger
787               policy, require the container itself to resize. As mentioned
788               above, the hash-based containers themselves do not contain
789               these types of methods, only their resize policies.
790               Consequently, there must be some mechanism for a resize policy
791               to manipulate the hash-based container. As the hash-based
792               container is a subclass of the resize policy, this is done
793               through virtual methods. Each hash-based container has a
794               <code class="classname">private</code> <code class="classname">virtual</code> method:</p><pre class="programlisting">
795                 virtual void
796                 do_resize
797                 (size_type new_size);
798               </pre><p>which resizes the container. Implementations of
799               <code class="classname">Resize_Policy</code> can export public methods for resizing
800               the container externally; these methods internally call
801               <code class="classname">do_resize</code> to resize the table.</p></div></div></div><div class="section" title="Policy Interactions"><div class="titlepage"><div><div><h6 class="title"><a id="container.hash.details.policy_interaction"/>Policy Interactions</h6></div></div></div><p>
802           </p><p>Hash-tables are unfortunately especially susceptible to
803           choice of policies. One of the more complicated aspects of this
804           is that poor combinations of good policies can form a poor
805           container. Following are some considerations.</p><div class="section" title="probe/size/trigger"><div class="titlepage"><div><div><h6 class="title"><a id="policy_interaction.probesizetrigger"/>probe/size/trigger</h6></div></div></div><p>Some combinations do not work well for probing containers.
806             For example, combining a quadratic probe policy with an
807             exponential size policy can yield a poor container: when an
808             element is inserted, a trigger policy might decide that there
809             is no need to resize, as the table still contains unused
810             entries; the probe sequence, however, might never reach any of
811             the unused entries.</p><p>Unfortunately, this library cannot detect such problems at
812             compilation (they are halting reducible). It therefore defines
813             an exception class <code class="classname">insert_error</code> to throw an
814             exception in this case.</p></div><div class="section" title="hash/trigger"><div class="titlepage"><div><div><h6 class="title"><a id="policy_interaction.hashtrigger"/>hash/trigger</h6></div></div></div><p>Some trigger policies are especially susceptible to poor
815             hash functions. Suppose, as an extreme case, that the hash
816             function transforms each key to the same hash value. After some
817             inserts, a collision detecting policy will always indicate that
818             the container needs to grow.</p><p>The library, therefore, by design, limits each operation to
819             one resize. For each <code class="classname">insert</code>, for example, it queries
820             only once whether a resize is needed.</p></div><div class="section" title="equivalence functors/storing hash values/hash"><div class="titlepage"><div><div><h6 class="title"><a id="policy_interaction.eqstorehash"/>equivalence functors/storing hash values/hash</h6></div></div></div><p><code class="classname">cc_hash_table</code> and
821             <code class="classname">gp_hash_table</code> are
822             parametrized by an equivalence functor and by a
823             <code class="classname">Store_Hash</code> parameter. If the latter parameter is
824             <code class="classname">true</code>, then the container stores with each entry
825             a hash value, and uses this value in case of collisions to
826             determine whether to apply a hash value. This can lower the
827             cost of collision for some types, but increase the cost of
828             collisions for other types.</p><p>If a ranged-hash function or ranged probe function is
829             directly supplied, however, then it makes no sense to store the
830             hash value with each entry. This library's container will
831             fail at compilation, by design, if this is attempted.</p></div><div class="section" title="size/load-check trigger"><div class="titlepage"><div><div><h6 class="title"><a id="policy_interaction.sizeloadtrigger"/>size/load-check trigger</h6></div></div></div><p>Assume a size policy issues an increasing sequence of sizes
832             a, a q, a q<sup>1</sup>, a q<sup>2</sup>, ... For
833             example, an exponential size policy might issue the sequence of
834             sizes 8, 16, 32, 64, ...</p><p>If a load-check trigger policy is used, with loads
835             α<sub>min</sub> and α<sub>max</sub>,
836             respectively, then it is a good idea to have:</p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p>α<sub>max</sub> ~ 1 / q</p></li><li class="listitem"><p>α<sub>min</sub> &lt; 1 / (2 q)</p></li></ol></div><p>This will ensure that the amortized hash cost of each
837             modifying operation is at most approximately 3.</p><p>α<sub>min</sub> ~ α<sub>max</sub> is, in
838             any case, a bad choice, and α<sub>min</sub> &gt;
839             α <sub>max</sub> is horrendous.</p></div></div></div></div><div class="section" title="tree"><div class="titlepage"><div><div><h4 class="title"><a id="pbds.design.container.tree"/>tree</h4></div></div></div><div class="section" title="Interface"><div class="titlepage"><div><div><h5 class="title"><a id="container.tree.interface"/>Interface</h5></div></div></div><p>The tree-based container has the following declaration:</p><pre class="programlisting">
840           template&lt;
841           typename Key,
842           typename Mapped,
843           typename Cmp_Fn = std::less&lt;Key&gt;,
844           typename Tag = rb_tree_tag,
845           template&lt;
846           typename Const_Node_Iterator,
847           typename Node_Iterator,
848           typename Cmp_Fn_,
849           typename Allocator_&gt;
850           class Node_Update = null_node_update,
851           typename Allocator = std::allocator&lt;char&gt; &gt;
852           class tree;
853         </pre><p>The parameters have the following meaning:</p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p><code class="classname">Key</code> is the key type.</p></li><li class="listitem"><p><code class="classname">Mapped</code> is the mapped-policy.</p></li><li class="listitem"><p><code class="classname">Cmp_Fn</code> is a key comparison functor</p></li><li class="listitem"><p><code class="classname">Tag</code> specifies which underlying data structure
854           to use.</p></li><li class="listitem"><p><code class="classname">Node_Update</code> is a policy for updating node
855           invariants.</p></li><li class="listitem"><p><code class="classname">Allocator</code> is an allocator
856           type.</p></li></ol></div><p>The <code class="classname">Tag</code> parameter specifies which underlying
857         data structure to use. Instantiating it by <code class="classname">rb_tree_tag</code>, <code class="classname">splay_tree_tag</code>, or
858         <code class="classname">ov_tree_tag</code>,
859         specifies an underlying red-black tree, splay tree, or
860         ordered-vector tree, respectively; any other tag is illegal.
861         Note that containers based on the former two contain more types
862         and methods than the latter (e.g.,
863         <code class="classname">reverse_iterator</code> and <code class="classname">rbegin</code>), and different
864         exception and invalidation guarantees.</p></div><div class="section" title="Details"><div class="titlepage"><div><div><h5 class="title"><a id="container.tree.details"/>Details</h5></div></div></div><div class="section" title="Node Invariants"><div class="titlepage"><div><div><h6 class="title"><a id="container.tree.node"/>Node Invariants</h6></div></div></div><p>Consider the two trees in the graphic below, labels A and B. The first
865           is a tree of floats; the second is a tree of pairs, each
866           signifying a geometric line interval. Each element in a tree is refered to as a node of the tree. Of course, each of
867           these trees can support the usual queries: the first can easily
868           search for <code class="classname">0.4</code>; the second can easily search for
869           <code class="classname">std::make_pair(10, 41)</code>.</p><p>Each of these trees can efficiently support other queries.
870           The first can efficiently determine that the 2rd key in the
871           tree is <code class="constant">0.3</code>; the second can efficiently determine
872           whether any of its intervals overlaps
873           </p><pre class="programlisting">std::make_pair(29,42)</pre><p> (useful in geometric
874           applications or distributed file systems with leases, for
875           example).  It should be noted that an <code class="classname">std::set</code> can
876           only solve these types of problems with linear complexity.</p><p>In order to do so, each tree stores some metadata in
877           each node, and maintains node invariants (see <a class="xref" href="policy_data_structures.html#biblio.clrs2001" title="Introduction to Algorithms, 2nd edition">[biblio.clrs2001]</a>.) The first stores in
878           each node the size of the sub-tree rooted at the node; the
879           second stores at each node the maximal endpoint of the
880           intervals at the sub-tree rooted at the node.</p><div class="figure"><a id="id522406"/><p class="title"><strong>Figure 22.22. Tree node invariants</strong></p><div class="figure-contents"><div class="mediaobject" style="text-align: center"><img src="../images/pbds_tree_node_invariants.png" style="text-align: middle" alt="Tree node invariants"/></div></div></div><br class="figure-break"/><p>Supporting such trees is difficult for a number of
881           reasons:</p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p>There must be a way to specify what a node's metadata
882             should be (if any).</p></li><li class="listitem"><p>Various operations can invalidate node
883             invariants.  The graphic below shows how a right rotation,
884             performed on A, results in B, with nodes x and y having
885             corrupted invariants (the grayed nodes in C). The graphic shows
886             how an insert, performed on D, results in E, with nodes x and y
887             having corrupted invariants (the grayed nodes in F). It is not
888             feasible to know outside the tree the effect of an operation on
889             the nodes of the tree.</p></li><li class="listitem"><p>The search paths of standard associative containers are
890             defined by comparisons between keys, and not through
891             metadata.</p></li><li class="listitem"><p>It is not feasible to know in advance which methods trees
892             can support. Besides the usual <code class="classname">find</code> method, the
893             first tree can support a <code class="classname">find_by_order</code> method, while
894             the second can support an <code class="classname">overlaps</code> method.</p></li></ol></div><div class="figure"><a id="id522484"/><p class="title"><strong>Figure 22.23. Tree node invalidation</strong></p><div class="figure-contents"><div class="mediaobject" style="text-align: center"><img src="../images/pbds_tree_node_invalidations.png" style="text-align: middle" alt="Tree node invalidation"/></div></div></div><br class="figure-break"/><p>These problems are solved by a combination of two means:
895           node iterators, and template-template node updater
896           parameters.</p><div class="section" title="Node Iterators"><div class="titlepage"><div><div><h6 class="title"><a id="container.tree.node.iterators"/>Node Iterators</h6></div></div></div><p>Each tree-based container defines two additional iterator
897             types, <code class="classname">const_node_iterator</code>
898             and <code class="classname">node_iterator</code>.
899             These iterators allow descending from a node to one of its
900             children. Node iterator allow search paths different than those
901             determined by the comparison functor. The <code class="classname">tree</code>
902             supports the methods:</p><pre class="programlisting">
903               const_node_iterator
904               node_begin() const;
905
906               node_iterator
907               node_begin();
908
909               const_node_iterator
910               node_end() const;
911
912               node_iterator
913               node_end(); 
914             </pre><p>The first pairs return node iterators corresponding to the
915             root node of the tree; the latter pair returns node iterators
916             corresponding to a just-after-leaf node.</p></div><div class="section" title="Node Updator"><div class="titlepage"><div><div><h6 class="title"><a id="container.tree.node.updator"/>Node Updator</h6></div></div></div><p>The tree-based containers are parametrized by a
917             <code class="classname">Node_Update</code> template-template parameter. A
918             tree-based container instantiates
919             <code class="classname">Node_Update</code> to some
920             <code class="classname">node_update</code> class, and publicly subclasses
921             <code class="classname">node_update</code>. The graphic below shows this
922             scheme, as well as some predefined policies (which are explained
923             below).</p><div class="figure"><a id="id522594"/><p class="title"><strong>Figure 22.24. A tree and its update policy</strong></p><div class="figure-contents"><div class="mediaobject" style="text-align: center"><img src="../images/pbds_tree_node_updator_policy_cd.png" style="text-align: middle" alt="A tree and its update policy"/></div></div></div><br class="figure-break"/><p><code class="classname">node_update</code> (an instantiation of
924             <code class="classname">Node_Update</code>) must define <code class="classname">metadata_type</code> as
925             the type of metadata it requires. For order statistics,
926             e.g., <code class="classname">metadata_type</code> might be <code class="classname">size_t</code>.
927             The tree defines within each node a <code class="classname">metadata_type</code>
928             object.</p><p><code class="classname">node_update</code> must also define the following method
929             for restoring node invariants:</p><pre class="programlisting">
930               void 
931               operator()(node_iterator nd_it, const_node_iterator end_nd_it)
932             </pre><p>In this method, <code class="varname">nd_it</code> is a
933             <code class="classname">node_iterator</code> corresponding to a node whose
934             A) all descendants have valid invariants, and B) its own
935             invariants might be violated; <code class="classname">end_nd_it</code> is
936             a <code class="classname">const_node_iterator</code> corresponding to a
937             just-after-leaf node. This method should correct the node
938             invariants of the node pointed to by
939             <code class="classname">nd_it</code>. For example, say node x in the
940             graphic below label A has an invalid invariant, but its' children,
941             y and z have valid invariants. After the invocation, all three
942             nodes should have valid invariants, as in label B.</p><div class="figure"><a id="id522691"/><p class="title"><strong>Figure 22.25. Restoring node invariants</strong></p><div class="figure-contents"><div class="mediaobject" style="text-align: center"><img src="../images/pbds_restoring_node_invariants.png" style="text-align: middle" alt="Restoring node invariants"/></div></div></div><br class="figure-break"/><p>When a tree operation might invalidate some node invariant,
943             it invokes this method in its <code class="classname">node_update</code> base to
944             restore the invariant. For example, the graphic below shows
945             an <code class="function">insert</code> operation (point A); the tree performs some
946             operations, and calls the update functor three times (points B,
947             C, and D). (It is well known that any <code class="function">insert</code>,
948             <code class="function">erase</code>, <code class="function">split</code> or <code class="function">join</code>, can restore
949             all node invariants by a small number of node invariant updates (<a class="xref" href="policy_data_structures.html#biblio.clrs2001" title="Introduction to Algorithms, 2nd edition">[biblio.clrs2001]</a>)
950             .</p><div class="figure"><a id="id522759"/><p class="title"><strong>Figure 22.26. Insert update sequence</strong></p><div class="figure-contents"><div class="mediaobject" style="text-align: center"><img src="../images/pbds_update_seq_diagram.png" style="text-align: middle" alt="Insert update sequence"/></div></div></div><br class="figure-break"/><p>To complete the description of the scheme, three questions
951             need to be answered:</p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p>How can a tree which supports order statistics define a
952               method such as <code class="classname">find_by_order</code>?</p></li><li class="listitem"><p>How can the node updater base access methods of the
953               tree?</p></li><li class="listitem"><p>How can the following cyclic dependency be resolved?
954               <code class="classname">node_update</code> is a base class of the tree, yet it
955               uses node iterators defined in the tree (its child).</p></li></ol></div><p>The first two questions are answered by the fact that
956             <code class="classname">node_update</code> (an instantiation of
957             <code class="classname">Node_Update</code>) is a <span class="emphasis"><em>public</em></span> base class
958             of the tree. Consequently:</p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p>Any public methods of
959               <code class="classname">node_update</code> are automatically methods of
960               the tree (<a class="xref" href="policy_data_structures.html#biblio.alexandrescu01modern" title="Modern C++ Design: Generic Programming and Design Patterns Applied">[biblio.alexandrescu01modern]</a>).
961               Thus an order-statistics node updater,
962               <code class="classname">tree_order_statistics_node_update</code> defines
963               the <code class="function">find_by_order</code> method; any tree
964               instantiated by this policy consequently supports this method as
965               well.</p></li><li class="listitem"><p>In C++, if a base class declares a method as
966               <code class="literal">virtual</code>, it is
967               <code class="literal">virtual</code> in its subclasses. If
968               <code class="classname">node_update</code> needs to access one of the
969               tree's methods, say the member function
970               <code class="function">end</code>, it simply declares that method as
971               <code class="literal">virtual</code> abstract.</p></li></ol></div><p>The cyclic dependency is solved through template-template
972             parameters. <code class="classname">Node_Update</code> is parametrized by
973             the tree's node iterators, its comparison functor, and its
974             allocator type. Thus, instantiations of
975             <code class="classname">Node_Update</code> have all information
976             required.</p><p>This library assumes that constructing a metadata object and
977             modifying it are exception free. Suppose that during some method,
978             say <code class="classname">insert</code>, a metadata-related operation
979             (e.g., changing the value of a metadata) throws an exception. Ack!
980             Rolling back the method is unusually complex.</p><p>Previously, a distinction was made between redundant
981             policies and null policies. Node invariants show a
982             case where null policies are required.</p><p>Assume a regular tree is required, one which need not
983             support order statistics or interval overlap queries.
984             Seemingly, in this case a redundant policy - a policy which
985             doesn't affect nodes' contents would suffice. This, would lead
986             to the following drawbacks:</p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p>Each node would carry a useless metadata object, wasting
987               space.</p></li><li class="listitem"><p>The tree cannot know if its
988               <code class="classname">Node_Update</code> policy actually modifies a
989               node's metadata (this is halting reducible). In the graphic
990               below, assume the shaded node is inserted. The tree would have
991               to traverse the useless path shown to the root, applying
992               redundant updates all the way.</p></li></ol></div><div class="figure"><a id="id522945"/><p class="title"><strong>Figure 22.27. Useless update path</strong></p><div class="figure-contents"><div class="mediaobject" style="text-align: center"><img src="../images/pbds_rationale_null_node_updator.png" style="text-align: middle" alt="Useless update path"/></div></div></div><br class="figure-break"/><p>A null policy class, <code class="classname">null_node_update</code>
993             solves both these problems. The tree detects that node
994             invariants are irrelevant, and defines all accordingly.</p></div></div><div class="section" title="Split and Join"><div class="titlepage"><div><div><h6 class="title"><a id="container.tree.details.split"/>Split and Join</h6></div></div></div><p>Tree-based containers support split and join methods.
995           It is possible to split a tree so that it passes
996           all nodes with keys larger than a given key to a different
997           tree. These methods have the following advantages over the
998           alternative of externally inserting to the destination
999           tree and erasing from the source tree:</p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p>These methods are efficient - red-black trees are split
1000             and joined in poly-logarithmic complexity; ordered-vector
1001             trees are split and joined at linear complexity. The
1002             alternatives have super-linear complexity.</p></li><li class="listitem"><p>Aside from orders of growth, these operations perform
1003             few allocations and de-allocations. For red-black trees, allocations are not performed,
1004             and the methods are exception-free. </p></li></ol></div></div></div></div><div class="section" title="Trie"><div class="titlepage"><div><div><h4 class="title"><a id="pbds.design.container.trie"/>Trie</h4></div></div></div><div class="section" title="Interface"><div class="titlepage"><div><div><h5 class="title"><a id="container.trie.interface"/>Interface</h5></div></div></div><p>The trie-based container has the following declaration:</p><pre class="programlisting">
1005           template&lt;typename Key,
1006           typename Mapped,
1007           typename Cmp_Fn = std::less&lt;Key&gt;,
1008           typename Tag = pat_trie_tag,
1009           template&lt;typename Const_Node_Iterator,
1010           typename Node_Iterator,
1011           typename E_Access_Traits_,
1012           typename Allocator_&gt;
1013           class Node_Update = null_node_update,
1014           typename Allocator = std::allocator&lt;char&gt; &gt;
1015           class trie;
1016         </pre><p>The parameters have the following meaning:</p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p><code class="classname">Key</code> is the key type.</p></li><li class="listitem"><p><code class="classname">Mapped</code> is the mapped-policy.</p></li><li class="listitem"><p><code class="classname">E_Access_Traits</code> is described in below.</p></li><li class="listitem"><p><code class="classname">Tag</code> specifies which underlying data structure
1017           to use, and is described shortly.</p></li><li class="listitem"><p><code class="classname">Node_Update</code> is a policy for updating node
1018           invariants. This is described below.</p></li><li class="listitem"><p><code class="classname">Allocator</code> is an allocator
1019           type.</p></li></ol></div><p>The <code class="classname">Tag</code> parameter specifies which underlying
1020         data structure to use. Instantiating it by <code class="classname">pat_trie_tag</code>, specifies an
1021         underlying PATRICIA trie (explained shortly); any other tag is
1022         currently illegal.</p><p>Following is a description of a (PATRICIA) trie
1023         (this implementation follows <a class="xref" href="policy_data_structures.html#biblio.okasaki98mereable" title="Fast mergeable integer maps">[biblio.okasaki98mereable]</a> and 
1024         <a class="xref" href="policy_data_structures.html#biblio.filliatre2000ptset" title="Ptset: Sets of integers implemented as Patricia trees">[biblio.filliatre2000ptset]</a>). 
1025         </p><p>A (PATRICIA) trie is similar to a tree, but with the
1026         following differences:</p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p>It explicitly views keys as a sequence of elements.
1027           E.g., a trie can view a string as a sequence of
1028           characters; a trie can view a number as a sequence of
1029           bits.</p></li><li class="listitem"><p>It is not (necessarily) binary. Each node has fan-out n
1030           + 1, where n is the number of distinct
1031           elements.</p></li><li class="listitem"><p>It stores values only at leaf nodes.</p></li><li class="listitem"><p>Internal nodes have the properties that A) each has at
1032           least two children, and B) each shares the same prefix with
1033           any of its descendant.</p></li></ol></div><p>A (PATRICIA) trie has some useful properties:</p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p>It can be configured to use large node fan-out, giving it
1034           very efficient find performance (albeit at insertion
1035           complexity and size).</p></li><li class="listitem"><p>It works well for common-prefix keys.</p></li><li class="listitem"><p>It can support efficiently queries such as which
1036           keys match a certain prefix. This is sometimes useful in file
1037           systems and routers, and for "type-ahead" aka predictive text matching
1038           on mobile devices.</p></li></ol></div></div><div class="section" title="Details"><div class="titlepage"><div><div><h5 class="title"><a id="container.trie.details"/>Details</h5></div></div></div><div class="section" title="Element Access Traits"><div class="titlepage"><div><div><h6 class="title"><a id="container.trie.details.etraits"/>Element Access Traits</h6></div></div></div><p>A trie inherently views its keys as sequences of elements.
1039           For example, a trie can view a string as a sequence of
1040           characters. A trie needs to map each of n elements to a
1041           number in {0, n - 1}. For example, a trie can map a
1042           character <code class="varname">c</code> to
1043           </p><pre class="programlisting">static_cast&lt;size_t&gt;(c)</pre><p>.</p><p>Seemingly, then, a trie can assume that its keys support
1044           (const) iterators, and that the <code class="classname">value_type</code> of this
1045           iterator can be cast to a <code class="classname">size_t</code>. There are several
1046           reasons, though, to decouple the mechanism by which the trie
1047           accesses its keys' elements from the trie:</p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p>In some cases, the numerical value of an element is
1048             inappropriate. Consider a trie storing DNA strings. It is
1049             logical to use a trie with a fan-out of 5 = 1 + |{'A', 'C',
1050             'G', 'T'}|. This requires mapping 'T' to 3, though.</p></li><li class="listitem"><p>In some cases the keys' iterators are different than what
1051             is needed. For example, a trie can be used to search for
1052             common suffixes, by using strings'
1053             <code class="classname">reverse_iterator</code>. As another example, a trie mapping
1054             UNICODE strings would have a huge fan-out if each node would
1055             branch on a UNICODE character; instead, one can define an
1056             iterator iterating over 8-bit (or less) groups.</p></li></ol></div><p>trie is,
1057           consequently, parametrized by <code class="classname">E_Access_Traits</code> -
1058           traits which instruct how to access sequences' elements.
1059           <code class="classname">string_trie_e_access_traits</code>
1060           is a traits class for strings. Each such traits define some
1061           types, like:</p><pre class="programlisting">
1062             typename E_Access_Traits::const_iterator
1063           </pre><p>is a const iterator iterating over a key's elements. The
1064           traits class must also define methods for obtaining an iterator
1065           to the first and last element of a key.</p><p>The graphic below shows a
1066           (PATRICIA) trie resulting from inserting the words: "I wish
1067           that I could ever see a poem lovely as a trie" (which,
1068           unfortunately, does not rhyme).</p><p>The leaf nodes contain values; each internal node contains
1069           two <code class="classname">typename E_Access_Traits::const_iterator</code>
1070           objects, indicating the maximal common prefix of all keys in
1071           the sub-tree. For example, the shaded internal node roots a
1072           sub-tree with leafs "a" and "as". The maximal common prefix is
1073           "a". The internal node contains, consequently, to const
1074           iterators, one pointing to <code class="varname">'a'</code>, and the other to
1075           <code class="varname">'s'</code>.</p><div class="figure"><a id="id523317"/><p class="title"><strong>Figure 22.28. A PATRICIA trie</strong></p><div class="figure-contents"><div class="mediaobject" style="text-align: center"><img src="../images/pbds_pat_trie.png" style="text-align: middle" alt="A PATRICIA trie"/></div></div></div><br class="figure-break"/></div><div class="section" title="Node Invariants"><div class="titlepage"><div><div><h6 class="title"><a id="container.trie.details.node"/>Node Invariants</h6></div></div></div><p>Trie-based containers support node invariants, as do
1076           tree-based containers. There are two minor
1077           differences, though, which, unfortunately, thwart sharing them
1078           sharing the same node-updating policies:</p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p>A trie's <code class="classname">Node_Update</code> template-template
1079               parameter is parametrized by <code class="classname">E_Access_Traits</code>, while
1080               a tree's <code class="classname">Node_Update</code> template-template parameter is
1081             parametrized by <code class="classname">Cmp_Fn</code>.</p></li><li class="listitem"><p>Tree-based containers store values in all nodes, while
1082             trie-based containers (at least in this implementation) store
1083             values in leafs.</p></li></ol></div><p>The graphic below shows the scheme, as well as some predefined
1084           policies (which are explained below).</p><div class="figure"><a id="id523405"/><p class="title"><strong>Figure 22.29. A trie and its update policy</strong></p><div class="figure-contents"><div class="mediaobject" style="text-align: center"><img src="../images/pbds_trie_node_updator_policy_cd.png" style="text-align: middle" alt="A trie and its update policy"/></div></div></div><br class="figure-break"/><p>This library offers the following pre-defined trie node
1085           updating policies:</p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p>
1086                 <code class="classname">trie_order_statistics_node_update</code>
1087                 supports order statistics.
1088               </p></li><li class="listitem"><p><code class="classname">trie_prefix_search_node_update</code>
1089             supports searching for ranges that match a given prefix.</p></li><li class="listitem"><p><code class="classname">null_node_update</code>
1090             is the null node updater.</p></li></ol></div></div><div class="section" title="Split and Join"><div class="titlepage"><div><div><h6 class="title"><a id="container.trie.details.split"/>Split and Join</h6></div></div></div><p>Trie-based containers support split and join methods; the
1091           rationale is equal to that of tree-based containers supporting
1092           these methods.</p></div></div></div><div class="section" title="List"><div class="titlepage"><div><div><h4 class="title"><a id="pbds.design.container.list"/>List</h4></div></div></div><div class="section" title="Interface"><div class="titlepage"><div><div><h5 class="title"><a id="container.list.interface"/>Interface</h5></div></div></div><p>The list-based container has the following declaration:</p><pre class="programlisting">
1093           template&lt;typename Key,
1094           typename Mapped,
1095           typename Eq_Fn = std::equal_to&lt;Key&gt;,
1096           typename Update_Policy = move_to_front_lu_policy&lt;&gt;,
1097           typename Allocator = std::allocator&lt;char&gt; &gt;
1098           class list_update;
1099         </pre><p>The parameters have the following meaning:</p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p>
1100               <code class="classname">Key</code> is the key type.
1101             </p></li><li class="listitem"><p>
1102               <code class="classname">Mapped</code> is the mapped-policy.
1103             </p></li><li class="listitem"><p>
1104               <code class="classname">Eq_Fn</code> is a key equivalence functor.
1105             </p></li><li class="listitem"><p>
1106               <code class="classname">Update_Policy</code> is a policy updating positions in
1107               the list based on access patterns. It is described in the
1108               following subsection.
1109             </p></li><li class="listitem"><p>
1110               <code class="classname">Allocator</code> is an allocator type.
1111             </p></li></ol></div><p>A list-based associative container is a container that
1112         stores elements in a linked-list. It does not order the elements
1113         by any particular order related to the keys.  List-based
1114         containers are primarily useful for creating "multimaps". In fact,
1115         list-based containers are designed in this library expressly for
1116         this purpose.</p><p>List-based containers might also be useful for some rare
1117         cases, where a key is encapsulated to the extent that only
1118         key-equivalence can be tested. Hash-based containers need to know
1119         how to transform a key into a size type, and tree-based containers
1120         need to know if some key is larger than another.  List-based
1121         associative containers, conversely, only need to know if two keys
1122         are equivalent.</p><p>Since a list-based associative container does not order
1123         elements by keys, is it possible to order the list in some
1124         useful manner? Remarkably, many on-line competitive
1125         algorithms exist for reordering lists to reflect access
1126         prediction. (See <a class="xref" href="policy_data_structures.html#biblio.motwani95random" title="Randomized Algorithms">[biblio.motwani95random]</a> and <a class="xref" href="policy_data_structures.html#biblio.andrew04mtf" title="MTF, Bit, and COMB: A Guide to Deterministic and Randomized Algorithms for the List Update Problem">[biblio.andrew04mtf]</a>).
1127         </p></div><div class="section" title="Details"><div class="titlepage"><div><div><h5 class="title"><a id="container.list.details"/>Details</h5></div></div></div><p>
1128         </p><div class="section" title="Underlying Data Structure"><div class="titlepage"><div><div><h6 class="title"><a id="container.list.details.ds"/>Underlying Data Structure</h6></div></div></div><p>The graphic below shows a
1129           simple list of integer keys. If we search for the integer 6, we
1130           are paying an overhead: the link with key 6 is only the fifth
1131           link; if it were the first link, it could be accessed
1132           faster.</p><div class="figure"><a id="id523660"/><p class="title"><strong>Figure 22.30. A simple list</strong></p><div class="figure-contents"><div class="mediaobject" style="text-align: center"><img src="../images/pbds_simple_list.png" style="text-align: middle" alt="A simple list"/></div></div></div><br class="figure-break"/><p>List-update algorithms reorder lists as elements are
1133           accessed. They try to determine, by the access history, which
1134           keys to move to the front of the list. Some of these algorithms
1135           require adding some metadata alongside each entry.</p><p>For example, in the graphic below label A shows the counter
1136           algorithm. Each node contains both a key and a count metadata
1137           (shown in bold). When an element is accessed (e.g. 6) its count is
1138           incremented, as shown in label B. If the count reaches some
1139           predetermined value, say 10, as shown in label C, the count is set
1140           to 0 and the node is moved to the front of the list, as in label
1141           D.
1142           </p><div class="figure"><a id="id523706"/><p class="title"><strong>Figure 22.31. The counter algorithm</strong></p><div class="figure-contents"><div class="mediaobject" style="text-align: center"><img src="../images/pbds_list_update.png" style="text-align: middle" alt="The counter algorithm"/></div></div></div><br class="figure-break"/></div><div class="section" title="Policies"><div class="titlepage"><div><div><h6 class="title"><a id="container.list.details.policies"/>Policies</h6></div></div></div><p>this library allows instantiating lists with policies
1143           implementing any algorithm moving nodes to the front of the
1144           list (policies implementing algorithms interchanging nodes are
1145           unsupported).</p><p>Associative containers based on lists are parametrized by a
1146           <code class="classname">Update_Policy</code> parameter. This parameter defines the
1147           type of metadata each node contains, how to create the
1148           metadata, and how to decide, using this metadata, whether to
1149           move a node to the front of the list. A list-based associative
1150           container object derives (publicly) from its update policy.
1151           </p><p>An instantiation of <code class="classname">Update_Policy</code> must define
1152           internally <code class="classname">update_metadata</code> as the metadata it
1153           requires. Internally, each node of the list contains, besides
1154           the usual key and data, an instance of <code class="classname">typename
1155           Update_Policy::update_metadata</code>.</p><p>An instantiation of <code class="classname">Update_Policy</code> must define
1156           internally two operators:</p><pre class="programlisting">
1157             update_metadata
1158             operator()();
1159
1160             bool
1161             operator()(update_metadata &amp;);
1162           </pre><p>The first is called by the container object, when creating a
1163           new node, to create the node's metadata. The second is called
1164           by the container object, when a node is accessed (
1165           when a find operation's key is equivalent to the key of the
1166           node), to determine whether to move the node to the front of
1167           the list.
1168           </p><p>The library contains two predefined implementations of
1169           list-update policies. The first
1170           is <code class="classname">lu_counter_policy</code>, which implements the
1171           counter algorithm described above. The second is
1172           <code class="classname">lu_move_to_front_policy</code>,
1173           which unconditionally move an accessed element to the front of
1174           the list. The latter type is very useful in this library,
1175           since there is no need to associate metadata with each element.
1176           (See <a class="xref" href="policy_data_structures.html#biblio.andrew04mtf" title="MTF, Bit, and COMB: A Guide to Deterministic and Randomized Algorithms for the List Update Problem">[biblio.andrew04mtf]</a> 
1177           </p></div><div class="section" title="Use in Multimaps"><div class="titlepage"><div><div><h6 class="title"><a id="container.list.details.mapped"/>Use in Multimaps</h6></div></div></div><p>In this library, there are no equivalents for the standard's
1178           multimaps and multisets; instead one uses an associative
1179           container mapping primary keys to secondary keys.</p><p>List-based containers are especially useful as associative
1180           containers for secondary keys. In fact, they are implemented
1181           here expressly for this purpose.</p><p>To begin with, these containers use very little per-entry
1182           structure memory overhead, since they can be implemented as
1183           singly-linked lists. (Arrays use even lower per-entry memory
1184           overhead, but they are less flexible in moving around entries,
1185           and have weaker invalidation guarantees).</p><p>More importantly, though, list-based containers use very
1186           little per-container memory overhead. The memory overhead of an
1187           empty list-based container is practically that of a pointer.
1188           This is important for when they are used as secondary
1189           associative-containers in situations where the average ratio of
1190           secondary keys to primary keys is low (or even 1).</p><p>In order to reduce the per-container memory overhead as much
1191           as possible, they are implemented as closely as possible to
1192           singly-linked lists.</p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p>
1193                 List-based containers do not store internally the number
1194                 of values that they hold. This means that their <code class="function">size</code>
1195                 method has linear complexity (just like <code class="classname">std::list</code>).
1196                 Note that finding the number of equivalent-key values in a
1197                 standard multimap also has linear complexity (because it must be
1198                 done,  via <code class="function">std::distance</code> of the
1199                 multimap's <code class="function">equal_range</code> method), but usually with
1200                 higher constants.
1201               </p></li><li class="listitem"><p>
1202                 Most associative-container objects each hold a policy
1203                 object (a hash-based container object holds a
1204                 hash functor). List-based containers, conversely, only have
1205                 class-wide policy objects.
1206               </p></li></ol></div></div></div></div><div class="section" title="Priority Queue"><div class="titlepage"><div><div><h4 class="title"><a id="pbds.design.container.priority_queue"/>Priority Queue</h4></div></div></div><div class="section" title="Interface"><div class="titlepage"><div><div><h5 class="title"><a id="container.priority_queue.interface"/>Interface</h5></div></div></div><p>The priority queue container has the following
1207         declaration:
1208         </p><pre class="programlisting">
1209           template&lt;typename  Value_Type,
1210           typename  Cmp_Fn = std::less&lt;Value_Type&gt;,
1211           typename  Tag = pairing_heap_tag,
1212           typename  Allocator = std::allocator&lt;char &gt; &gt;
1213           class priority_queue;
1214         </pre><p>The parameters have the following meaning:</p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p><code class="classname">Value_Type</code> is the value type.</p></li><li class="listitem"><p><code class="classname">Cmp_Fn</code> is a value comparison functor</p></li><li class="listitem"><p><code class="classname">Tag</code> specifies which underlying data structure
1215           to use.</p></li><li class="listitem"><p><code class="classname">Allocator</code> is an allocator
1216           type.</p></li></ol></div><p>The <code class="classname">Tag</code> parameter specifies which underlying
1217         data structure to use. Instantiating it by<code class="classname">pairing_heap_tag</code>,<code class="classname">binary_heap_tag</code>,
1218         <code class="classname">binomial_heap_tag</code>,
1219         <code class="classname">rc_binomial_heap_tag</code>,
1220         or <code class="classname">thin_heap_tag</code>,
1221         specifies, respectively, 
1222         an underlying pairing heap (<a class="xref" href="policy_data_structures.html#biblio.fredman86pairing" title="The pairing heap: a new form of self-adjusting heap">[biblio.fredman86pairing]</a>),
1223         binary heap (<a class="xref" href="policy_data_structures.html#biblio.clrs2001" title="Introduction to Algorithms, 2nd edition">[biblio.clrs2001]</a>),
1224         binomial heap (<a class="xref" href="policy_data_structures.html#biblio.clrs2001" title="Introduction to Algorithms, 2nd edition">[biblio.clrs2001]</a>),
1225         a binomial heap with a redundant binary counter (<a class="xref" href="policy_data_structures.html#biblio.maverik_lowerbounds" title="Deamortization - Part 2: Binomial Heaps">[biblio.maverik_lowerbounds]</a>),
1226         or a thin heap (<a class="xref" href="policy_data_structures.html#biblio.kt99fat_heaps" title="New Heap Data Structures">[biblio.kt99fat_heaps]</a>).
1227         </p><p>
1228           As mentioned in the tutorial,
1229           <code class="classname">__gnu_pbds::priority_queue</code> shares most of the
1230           same interface with <code class="classname">std::priority_queue</code>.
1231           E.g. if <code class="varname">q</code> is a priority queue of type
1232           <code class="classname">Q</code>, then <code class="function">q.top()</code> will
1233           return the "largest" value in the container (according to
1234           <code class="classname">typename
1235           Q::cmp_fn</code>). <code class="classname">__gnu_pbds::priority_queue</code>
1236           has a larger (and very slightly different) interface than
1237           <code class="classname">std::priority_queue</code>, however, since typically
1238           <code class="classname">push</code> and <code class="classname">pop</code> are deemed
1239         insufficient for manipulating priority-queues. </p><p>Different settings require different priority-queue
1240         implementations which are described in later; see traits
1241         discusses ways to differentiate between the different traits of
1242         different implementations.</p></div><div class="section" title="Details"><div class="titlepage"><div><div><h5 class="title"><a id="container.priority_queue.details"/>Details</h5></div></div></div><div class="section" title="Iterators"><div class="titlepage"><div><div><h6 class="title"><a id="container.priority_queue.details.iterators"/>Iterators</h6></div></div></div><p>There are many different underlying-data structures for
1243           implementing priority queues. Unfortunately, most such
1244           structures are oriented towards making <code class="function">push</code> and
1245           <code class="function">top</code> efficient, and consequently don't allow efficient
1246           access of other elements: for instance, they cannot support an efficient
1247           <code class="function">find</code> method. In the use case where it
1248           is important to both access and "do something with" an
1249           arbitrary value, one would be out of luck. For example, many graph algorithms require
1250           modifying a value (typically increasing it in the sense of the
1251           priority queue's comparison functor).</p><p>In order to access and manipulate an arbitrary value in a
1252           priority queue, one needs to reference the internals of the
1253           priority queue from some form of an associative container -
1254           this is unavoidable. Of course, in order to maintain the
1255           encapsulation of the priority queue, this needs to be done in a
1256           way that minimizes exposure to implementation internals.</p><p>In this library the priority queue's <code class="function">insert</code>
1257           method returns an iterator, which if valid can be used for subsequent <code class="function">modify</code> and
1258           <code class="function">erase</code> operations. This both preserves the priority
1259           queue's encapsulation, and allows accessing arbitrary values (since the
1260           returned iterators from the <code class="function">push</code> operation can be
1261           stored in some form of associative container).</p><p>Priority queues' iterators present a problem regarding their
1262           invalidation guarantees. One assumes that calling
1263           <code class="function">operator++</code> on an iterator will associate it
1264           with the "next" value. Priority-queues are
1265           self-organizing: each operation changes what the "next" value
1266           means. Consequently, it does not make sense that <code class="function">push</code>
1267           will return an iterator that can be incremented - this can have
1268           no possible use. Also, as in the case of hash-based containers,
1269           it is awkward to define if a subsequent <code class="function">push</code> operation
1270           invalidates a prior returned iterator: it invalidates it in the
1271           sense that its "next" value is not related to what it
1272           previously considered to be its "next" value. However, it might not
1273           invalidate it, in the sense that it can be
1274           de-referenced and used for <code class="function">modify</code> and <code class="function">erase</code>
1275           operations.</p><p>Similarly to the case of the other unordered associative
1276           containers, this library uses a distinction between
1277           point-type and range type iterators. A priority queue's <code class="classname">iterator</code> can always be
1278           converted to a <code class="classname">point_iterator</code>, and a
1279           <code class="classname">const_iterator</code> can always be converted to a
1280           <code class="classname">point_const_iterator</code>.</p><p>The following snippet demonstrates manipulating an arbitrary
1281           value:</p><pre class="programlisting">
1282             // A priority queue of integers.
1283             priority_queue&lt;int &gt; p;
1284
1285             // Insert some values into the priority queue.
1286             priority_queue&lt;int &gt;::point_iterator it = p.push(0);
1287
1288             p.push(1);
1289             p.push(2);
1290
1291             // Now modify a value.
1292             p.modify(it, 3);
1293
1294             assert(p.top() == 3);
1295           </pre><p>It should be noted that an alternative design could embed an
1296           associative container in a priority queue. Could, but most
1297           probably should not. To begin with, it should be noted that one
1298           could always encapsulate a priority queue and an associative
1299           container mapping values to priority queue iterators with no
1300           performance loss. One cannot, however, "un-encapsulate" a priority
1301           queue embedding an associative container, which might lead to
1302           performance loss. Assume, that one needs to associate each value
1303           with some data unrelated to priority queues. Then using
1304           this library's design, one could use an
1305           associative container mapping each value to a pair consisting of
1306           this data and a priority queue's iterator. Using the embedded
1307           method would need to use two associative containers. Similar
1308           problems might arise in cases where a value can reside
1309           simultaneously in many priority queues.</p></div><div class="section" title="Underlying Data Structure"><div class="titlepage"><div><div><h6 class="title"><a id="container.priority_queue.details.d"/>Underlying Data Structure</h6></div></div></div><p>There are three main implementations of priority queues: the
1310           first employs a binary heap, typically one which uses a
1311           sequence; the second uses a tree (or forest of trees), which is
1312           typically less structured than an associative container's tree;
1313           the third simply uses an associative container. These are
1314           shown in the graphic below, in labels A1 and A2, label B, and label C.</p><div class="figure"><a id="id524238"/><p class="title"><strong>Figure 22.32. Underlying Priority-Queue Data-Structures.</strong></p><div class="figure-contents"><div class="mediaobject" style="text-align: center"><img src="../images/pbds_priority_queue_different_underlying_dss.png" style="text-align: middle" alt="Underlying Priority-Queue Data-Structures."/></div></div></div><br class="figure-break"/><p>Roughly speaking, any value that is both pushed and popped
1315           from a priority queue must incur a logarithmic expense (in the
1316           amortized sense). Any priority queue implementation that would
1317           avoid this, would violate known bounds on comparison-based
1318           sorting (see <a class="xref" href="policy_data_structures.html#biblio.clrs2001" title="Introduction to Algorithms, 2nd edition">[biblio.clrs2001]</a> and <a class="xref" href="policy_data_structures.html#biblio.brodal96priority" title="Worst-case efficient priority queues">[biblio.brodal96priority]</a>).
1319           </p><p>Most implementations do
1320           not differ in the asymptotic amortized complexity of
1321           <code class="function">push</code> and <code class="function">pop</code> operations, but they differ in
1322           the constants involved, in the complexity of other operations
1323           (e.g., <code class="function">modify</code>), and in the worst-case
1324           complexity of single operations. In general, the more
1325           "structured" an implementation (i.e., the more internal
1326           invariants it possesses) - the higher its amortized complexity
1327           of <code class="function">push</code> and <code class="function">pop</code> operations.</p><p>This library implements different algorithms using a
1328           single class: <code class="classname">priority_queue</code>.
1329           Instantiating the <code class="classname">Tag</code> template parameter, "selects"
1330           the implementation:</p><div class="orderedlist"><ol class="orderedlist"><li class="listitem"><p>
1331               Instantiating <code class="classname">Tag = binary_heap_tag</code> creates
1332               a binary heap of the form in represented in the graphic with labels A1 or A2. The former is internally
1333               selected by priority_queue
1334               if <code class="classname">Value_Type</code> is instantiated by a primitive type
1335               (e.g., an <span class="type">int</span>); the latter is
1336               internally selected for all other types (e.g.,
1337               <code class="classname">std::string</code>). This implementations is relatively
1338               unstructured, and so has good <code class="classname">push</code> and <code class="classname">pop</code>
1339               performance; it is the "best-in-kind" for primitive
1340               types, e.g., <span class="type">int</span>s. Conversely, it has
1341               high worst-case performance, and can support only linear-time
1342             <code class="function">modify</code> and <code class="function">erase</code> operations.</p></li><li class="listitem"><p>Instantiating <code class="classname">Tag =
1343             pairing_heap_tag</code> creates a pairing heap of the form
1344             in represented by label B in the graphic above. This
1345             implementations too is relatively unstructured, and so has good
1346             <code class="function">push</code> and <code class="function">pop</code>
1347             performance; it is the "best-in-kind" for non-primitive types,
1348             e.g., <code class="classname">std:string</code>s. It also has very good
1349             worst-case <code class="function">push</code> and
1350             <code class="function">join</code> performance (O(1)), but has high
1351             worst-case <code class="function">pop</code>
1352             complexity.</p></li><li class="listitem"><p>Instantiating <code class="classname">Tag =
1353             binomial_heap_tag</code> creates a binomial heap of the
1354             form repsented by label B in the graphic above. This
1355             implementations is more structured than a pairing heap, and so
1356             has worse <code class="function">push</code> and <code class="function">pop</code>
1357             performance. Conversely, it has sub-linear worst-case bounds for
1358             <code class="function">pop</code>, e.g., and so it might be preferred in
1359             cases where responsiveness is important.</p></li><li class="listitem"><p>Instantiating <code class="classname">Tag =
1360             rc_binomial_heap_tag</code> creates a binomial heap of the
1361             form represented in label B above, accompanied by a redundant
1362             counter which governs the trees. This implementations is
1363             therefore more structured than a binomial heap, and so has worse
1364             <code class="function">push</code> and <code class="function">pop</code>
1365             performance. Conversely, it guarantees O(1)
1366             <code class="function">push</code> complexity, and so it might be
1367             preferred in cases where the responsiveness of a binomial heap
1368             is insufficient.</p></li><li class="listitem"><p>Instantiating <code class="classname">Tag =
1369             thin_heap_tag</code> creates a thin heap of the form
1370             represented by the label B in the graphic above. This
1371             implementations too is more structured than a pairing heap, and
1372             so has worse <code class="function">push</code> and
1373             <code class="function">pop</code> performance. Conversely, it has better
1374             worst-case and identical amortized complexities than a Fibonacci
1375             heap, and so might be more appropriate for some graph
1376             algorithms.</p></li></ol></div><p>Of course, one can use any order-preserving associative
1377           container as a priority queue, as in the graphic above label C, possibly by creating an adapter class
1378           over the associative container (much as 
1379           <code class="classname">std::priority_queue</code> can adapt <code class="classname">std::vector</code>).
1380           This has the advantage that no cross-referencing is necessary
1381           at all; the priority queue itself is an associative container.
1382           Most associative containers are too structured to compete with
1383           priority queues in terms of <code class="function">push</code> and <code class="function">pop</code>
1384           performance.</p></div><div class="section" title="Traits"><div class="titlepage"><div><div><h6 class="title"><a id="container.priority_queue.details.traits"/>Traits</h6></div></div></div><p>It would be nice if all priority queues could
1385           share exactly the same behavior regardless of implementation. Sadly, this is not possible. Just one for instance is in join operations: joining
1386           two binary heaps might throw an exception (not corrupt
1387           any of the heaps on which it operates), but joining two pairing
1388           heaps is exception free.</p><p>Tags and traits are very useful for manipulating generic
1389           types. <code class="classname">__gnu_pbds::priority_queue</code>
1390           publicly defines <code class="classname">container_category</code> as one of the tags. Given any
1391           container <code class="classname">Cntnr</code>, the tag of the underlying
1392           data structure can be found via <code class="classname">typename 
1393           Cntnr::container_category</code>; this is one of the possible tags shown in the graphic below.
1394           </p><div class="figure"><a id="id524529"/><p class="title"><strong>Figure 22.33. Priority-Queue Data-Structure Tags.</strong></p><div class="figure-contents"><div class="mediaobject" style="text-align: center"><img src="../images/pbds_priority_queue_tag_hierarchy.png" style="text-align: middle" alt="Priority-Queue Data-Structure Tags."/></div></div></div><br class="figure-break"/><p>Additionally, a traits mechanism can be used to query a
1395           container type for its attributes. Given any container
1396           <code class="classname">Cntnr</code>, then </p><pre class="programlisting">__gnu_pbds::container_traits&lt;Cntnr&gt;</pre><p>
1397           is a traits class identifying the properties of the
1398           container.</p><p>To find if a container might throw if two of its objects are
1399           joined, one can use 
1400           </p><pre class="programlisting">
1401             container_traits&lt;Cntnr&gt;::split_join_can_throw
1402           </pre><p>
1403           </p><p>
1404             Different priority-queue implementations have different invalidation guarantees. This is
1405             especially important, since there is no way to access an arbitrary
1406             value of priority queues except for iterators. Similarly to
1407             associative containers, one can use
1408             </p><pre class="programlisting">
1409               container_traits&lt;Cntnr&gt;::invalidation_guarantee
1410             </pre><p>
1411           to get the invalidation guarantee type of a priority queue.</p><p>It is easy to understand from the graphic above, what <code class="classname">container_traits&lt;Cntnr&gt;::invalidation_guarantee</code>
1412           will be for different implementations. All implementations of
1413           type represented by label B have <code class="classname">point_invalidation_guarantee</code>:
1414           the container can freely internally reorganize the nodes -
1415           range-type iterators are invalidated, but point-type iterators
1416           are always valid. Implementations of type represented by labels A1 and A2 have <code class="classname">basic_invalidation_guarantee</code>:
1417           the container can freely internally reallocate the array - both
1418           point-type and range-type iterators might be invalidated.</p><p>
1419             This has major implications, and constitutes a good reason to avoid
1420             using binary heaps. A binary heap can perform <code class="function">modify</code>
1421             or <code class="function">erase</code> efficiently given a valid point-type
1422             iterator. However, in order to supply it with a valid point-type
1423             iterator, one needs to iterate (linearly) over all
1424             values, then supply the relevant iterator (recall that a
1425             range-type iterator can always be converted to a point-type
1426             iterator). This means that if the number of <code class="function">modify</code> or
1427             <code class="function">erase</code> operations is non-negligible (say
1428             super-logarithmic in the total sequence of operations) - binary
1429             heaps will perform badly.
1430           </p></div></div></div></div></div><div class="navfooter"><hr/><table width="100%" summary="Navigation footer"><tr><td align="left"><a accesskey="p" href="policy_data_structures_using.html">Prev</a> </td><td align="center"><a accesskey="u" href="policy_data_structures.html">Up</a></td><td align="right"> <a accesskey="n" href="policy_based_data_structures_test.html">Next</a></td></tr><tr><td align="left" valign="top">Using </td><td align="center"><a accesskey="h" href="../index.html">Home</a></td><td align="right" valign="top"> Testing</td></tr></table></div></body></html>