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