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