examples.html 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0.1 Transitional//EN">
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  5. <title>Boost.MultiIndex Documentation - Examples</title>
  6. <link rel="stylesheet" href="style.css" type="text/css">
  7. <link rel="start" href="index.html">
  8. <link rel="prev" href="performance.html">
  9. <link rel="up" href="index.html">
  10. <link rel="next" href="tests.html">
  11. </head>
  12. <body>
  13. <h1><img src="../../../boost.png" alt="boost.png (6897 bytes)" align=
  14. "middle" width="277" height="86">Boost.MultiIndex Examples</h1>
  15. <div class="prev_link"><a href="performance.html"><img src="prev.gif" alt="performance" border="0"><br>
  16. Performance
  17. </a></div>
  18. <div class="up_link"><a href="index.html"><img src="up.gif" alt="index" border="0"><br>
  19. Index
  20. </a></div>
  21. <div class="next_link"><a href="tests.html"><img src="next.gif" alt="tests" border="0"><br>
  22. Tests
  23. </a></div><br clear="all" style="clear: all;">
  24. <hr>
  25. <h2>Contents</h2>
  26. <ul>
  27. <li><a href="#example1">Example 1: basic usage</a></li>
  28. <li><a href="#example2">Example 2: using functions as keys</a></li>
  29. <li><a href="#example3">Example 3: constructing <code>multi_index_container</code>s
  30. with <code>ctor_args_list</code></a></li>
  31. <li><a href="#example4">Example 4: bidirectional map</a></li>
  32. <li><a href="#example5">Example 5: sequenced indices</a></li>
  33. <li><a href="#example6">Example 6: complex searches and foreign keys</a></li>
  34. <li><a href="#example7">Example 7: composite keys</a></li>
  35. <li><a href="#example8">Example 8: hashed indices</a></li>
  36. <li><a href="#example9">Example 9: serialization and MRU lists</a></li>
  37. <li><a href="#example10">Example 10: random access indices</a></li>
  38. <li><a href="#example11">Example 11: index rearrangement</a></li>
  39. <li><a href="#example12">Example 12: using Boost.Interprocess allocators</a></li>
  40. </ul>
  41. <h2><a name="example1">Example 1: basic usage</a></h2>
  42. <p>
  43. See <a href="../example/basic.cpp">source code</a>.
  44. </p>
  45. <p>
  46. Basic program showing the multi-indexing capabilities of Boost.MultiIndex
  47. with an admittedly boring set of <code>employee</code> records.
  48. </p>
  49. <h2><a name="example2">Example 2: using functions as keys</a></h2>
  50. <p>
  51. See <a href="../example/fun_key.cpp">source code</a>.
  52. </p>
  53. <p>
  54. Usually keys assigned to an index are based on a member variable of the
  55. element, but key extractors can be defined which take their value from
  56. a member function or a global function. This has some similarity with the concept of
  57. <i>calculated keys</i> supported by some relational database engines.
  58. The example shows how to use the predefined <code>const_mem_fun</code>
  59. and <code>global_fun</code> key extractors to deal with this situation.
  60. </p>
  61. <p>
  62. Keys based on functions usually will not be actual references,
  63. but rather the temporary values resulting from the invocation of the
  64. member function used. This implies that <code>modify_key</code> cannot be
  65. applied to this type of extractors, which is a perfectly logical
  66. constraint anyway.
  67. </p>
  68. <h2><a name="example3">Example 3: constructing <code>multi_index_container</code>s
  69. with <code>ctor_args_list</code></a></h2>
  70. <p>
  71. See <a href="../example/non_default_ctor.cpp">source code</a>.
  72. </p>
  73. <p>
  74. We show a practical example of usage of <code>multi_index_container::ctor_arg_list</code>,
  75. whose definition and purpose are explained in the
  76. <a href="tutorial/creation.html#ctor_args_list">tutorial</a>. The
  77. program groups a sorted collection of numbers based on identification through
  78. modulo arithmetics, by which <code>x</code> and <code>y</code> are equivalent
  79. if <code>(x%n)==(y%n)</code>, for some fixed <code>n</code>.
  80. </p>
  81. <h2><a name="example4">Example 4: bidirectional map</a></h2>
  82. <p>
  83. See <a href="../example/bimap.cpp">source code</a>.
  84. </p>
  85. <p>
  86. This example shows how to construct a bidirectional map with
  87. <code>multi_index_container</code>. By a <i>bidirectional map</i> we mean
  88. a container of <code>(const FromType,const ToType)</code> pairs
  89. such that no two elements exists with the same first
  90. <i>or</i> second component (<code>std::map</code> only
  91. guarantees uniqueness of the first component). Fast lookup is provided
  92. for both keys. The program features a tiny Spanish-English
  93. dictionary with online query of words in both languages.
  94. </p>
  95. <p>
  96. This bidirectional map can be considered as a primitive precursor
  97. to the full-fledged container provided by
  98. <a href="../../bimap/index.html">Boost.Bimap</a>.
  99. </p>
  100. <h2><a name="example5">Example 5: sequenced indices</a></h2>
  101. <p>
  102. See <a href="../example/sequenced.cpp">source code</a>.
  103. </p>
  104. <p>
  105. The combination of a sequenced index with an index of type <code>ordered_non_unique</code>
  106. yields a <code>list</code>-like structure with fast lookup capabilities. The
  107. example performs some operations on a given text, like word counting and
  108. selective deletion of some words.
  109. </p>
  110. <h2><a name="example6">Example 6: complex searches and foreign keys</a></h2>
  111. <p>
  112. See <a href="../example/complex_structs.cpp">source code</a>.
  113. </p>
  114. <p>
  115. This program illustrates some advanced techniques that can be applied
  116. for complex data structures using <code>multi_index_container</code>.
  117. Consider a <code>car_model</code> class for storing information
  118. about automobiles. On a first approach, <code>car_model</code> can
  119. be defined as:
  120. </p>
  121. <blockquote><pre>
  122. <span class=keyword>struct</span> <span class=identifier>car_model</span>
  123. <span class=special>{</span>
  124. <span class=identifier>std</span><span class=special>::</span><span class=identifier>string</span> <span class=identifier>model</span><span class=special>;</span>
  125. <span class=identifier>std</span><span class=special>::</span><span class=identifier>string</span> <span class=identifier>manufacturer</span><span class=special>;</span>
  126. <span class=keyword>int</span> <span class=identifier>price</span><span class=special>;</span>
  127. <span class=special>};</span>
  128. </pre></blockquote>
  129. <p>
  130. This definition has a design flaw that any reader acquainted with
  131. relational databases can easily spot: The <code>manufacturer</code>
  132. member is duplicated among all cars having the same manufacturer.
  133. This is a waste of space and poses difficulties when, for instance,
  134. the name of a manufacturer has to be changed. Following the usual
  135. principles in relational database design, the appropriate design
  136. involves having the manufactures stored in a separate
  137. <code>multi_index_container</code> and store pointers to these in
  138. <code>car_model</code>:
  139. </p>
  140. <blockquote><pre>
  141. <span class=keyword>struct</span> <span class=identifier>car_manufacturer</span>
  142. <span class=special>{</span>
  143. <span class=identifier>std</span><span class=special>::</span><span class=identifier>string</span> <span class=identifier>name</span><span class=special>;</span>
  144. <span class=special>};</span>
  145. <span class=keyword>struct</span> <span class=identifier>car_model</span>
  146. <span class=special>{</span>
  147. <span class=identifier>std</span><span class=special>::</span><span class=identifier>string</span> <span class=identifier>model</span><span class=special>;</span>
  148. <span class=identifier>car_manufacturer</span><span class=special>*</span> <span class=identifier>manufacturer</span><span class=special>;</span>
  149. <span class=keyword>int</span> <span class=identifier>price</span><span class=special>;</span>
  150. <span class=special>};</span>
  151. </pre></blockquote>
  152. <p>
  153. Although predefined Boost.MultiIndex key extractors can handle many
  154. situations involving pointers (see
  155. <a href="tutorial/key_extraction.html#advanced_key_extractors">advanced features
  156. of Boost.MultiIndex key extractors</a> in the tutorial), this case
  157. is complex enough that a suitable key extractor has to be defined. The following
  158. utility cascades two key extractors:
  159. </p>
  160. <blockquote><pre>
  161. <span class=keyword>template</span><span class=special>&lt;</span><span class=keyword>class</span> <span class=identifier>KeyExtractor1</span><span class=special>,</span><span class=keyword>class</span> <span class=identifier>KeyExtractor2</span><span class=special>&gt;</span>
  162. <span class=keyword>struct</span> <span class=identifier>key_from_key</span>
  163. <span class=special>{</span>
  164. <span class=keyword>public</span><span class=special>:</span>
  165. <span class=keyword>typedef</span> <span class=keyword>typename</span> <span class=identifier>KeyExtractor1</span><span class=special>::</span><span class=identifier>result_type</span> <span class=identifier>result_type</span><span class=special>;</span>
  166. <span class=identifier>key_from_key</span><span class=special>(</span>
  167. <span class=keyword>const</span> <span class=identifier>KeyExtractor1</span><span class=special>&amp;</span> <span class=identifier>key1_</span><span class=special>=</span><span class=identifier>KeyExtractor1</span><span class=special>(),</span>
  168. <span class=keyword>const</span> <span class=identifier>KeyExtractor2</span><span class=special>&amp;</span> <span class=identifier>key2_</span><span class=special>=</span><span class=identifier>KeyExtractor2</span><span class=special>()):</span>
  169. <span class=identifier>key1</span><span class=special>(</span><span class=identifier>key1_</span><span class=special>),</span><span class=identifier>key2</span><span class=special>(</span><span class=identifier>key2_</span><span class=special>)</span>
  170. <span class=special>{}</span>
  171. <span class=keyword>template</span><span class=special>&lt;</span><span class=keyword>typename</span> <span class=identifier>Arg</span><span class=special>&gt;</span>
  172. <span class=identifier>result_type</span> <span class=keyword>operator</span><span class=special>()(</span><span class=identifier>Arg</span><span class=special>&amp;</span> <span class=identifier>arg</span><span class=special>)</span><span class=keyword>const</span>
  173. <span class=special>{</span>
  174. <span class=keyword>return</span> <span class=identifier>key1</span><span class=special>(</span><span class=identifier>key2</span><span class=special>(</span><span class=identifier>arg</span><span class=special>));</span>
  175. <span class=special>}</span>
  176. <span class=keyword>private</span><span class=special>:</span>
  177. <span class=identifier>KeyExtractor1</span> <span class=identifier>key1</span><span class=special>;</span>
  178. <span class=identifier>KeyExtractor2</span> <span class=identifier>key2</span><span class=special>;</span>
  179. <span class=special>};</span>
  180. </pre></blockquote>
  181. <p>
  182. so that access from a <code>car_model</code> to the <code>name</code> field
  183. of its associated <code>car_manufacturer</code> can be accomplished with
  184. </p>
  185. <blockquote><pre>
  186. <span class=identifier>key_from_key</span><span class=special>&lt;</span>
  187. <span class=identifier>member</span><span class=special>&lt;</span><span class=identifier>car_manufacturer</span><span class=special>,</span><span class=keyword>const</span> <span class=identifier>std</span><span class=special>::</span><span class=identifier>string</span><span class=special>,&amp;</span><span class=identifier>car_manufacturer</span><span class=special>::</span><span class=identifier>name</span><span class=special>&gt;,</span>
  188. <span class=identifier>member</span><span class=special>&lt;</span><span class=identifier>car_model</span><span class=special>,</span><span class=keyword>const</span> <span class=identifier>car_manufacturer</span> <span class=special>*,</span><span class=identifier>car_model</span><span class=special>::</span><span class=identifier>manufacturer</span><span class=special>&gt;</span>
  189. <span class=special>&gt;</span>
  190. </pre></blockquote>
  191. <p>
  192. The program asks the user for a car manufacturer and a range of prices
  193. and returns the car models satisfying these requirements. This is a complex
  194. search that cannot be performed on a single operation. Broadly sketched,
  195. one procedure for executing the selection is:
  196. <ol>
  197. <li>Select the elements with the given manufacturer by means
  198. of <code>equal_range</code>,
  199. <li>feed these elements into a <code>multi_index_container</code> sorted
  200. by price,
  201. <li>select by price using <code>lower_bound</code> and
  202. <code>upper_bound</code>;
  203. </ol>
  204. or alternatively:
  205. <ol>
  206. <li>Select the elements within the price range with
  207. <code>lower_bound</code> and <code>upper_bound</code>,
  208. <li>feed these elements into a <code>multi_index_container</code> sorted
  209. by manufacturer,
  210. <li>locate the elements with given manufacturer using
  211. <code>equal_range</code>.
  212. </ol>
  213. An interesting technique developed in the example lies in
  214. the construction of the intermediate <code>multi_index_container</code>.
  215. In order to avoid object copying, appropriate <i>view</i> types
  216. are defined with <code>multi_index_container</code>s having as elements
  217. pointers to <code>car_model</code>s instead of actual objects.
  218. These views have to be supplemented with appropriate
  219. dereferencing key extractors.
  220. </p>
  221. <h2><a name="example7">Example 7: composite keys</a></h2>
  222. <p>
  223. See <a href="../example/composite_keys.cpp">source code</a>.
  224. </p>
  225. <p>
  226. Boost.MultiIndex <a href="tutorial/key_extraction.html#composite_keys">
  227. <code>composite_key</code></a> construct provides a flexible tool for
  228. creating indices with non-trivial sorting criteria.
  229. The program features a rudimentary simulation of a file system
  230. along with an interactive Unix-like shell. A file entry is represented by
  231. the following structure:
  232. </p>
  233. <blockquote><pre>
  234. <span class=keyword>struct</span> <span class=identifier>file_entry</span>
  235. <span class=special>{</span>
  236. <span class=identifier>std</span><span class=special>::</span><span class=identifier>string</span> <span class=identifier>name</span><span class=special>;</span>
  237. <span class=keyword>unsigned</span> <span class=identifier>size</span><span class=special>;</span>
  238. <span class=keyword>bool</span> <span class=identifier>is_dir</span><span class=special>;</span> <span class=comment>// true if the entry is a directory</span>
  239. <span class=keyword>const</span> <span class=identifier>file_entry</span><span class=special>*</span> <span class=identifier>dir</span><span class=special>;</span> <span class=comment>// directory this entry belongs in</span>
  240. <span class=special>};</span>
  241. </pre></blockquote>
  242. <p>
  243. Entries are kept in a <code>multi_index_container</code> maintaining two indices
  244. with composite keys:
  245. <ul>
  246. <li>A primary index ordered by directory and name,</li>
  247. <li>a secondary index ordered by directory and size.</li>
  248. </ul>
  249. The reason that the order is made firstly by the directory in which
  250. the files are located obeys to the local nature of the shell commands,
  251. like for instance <code>ls</code>. The shell simulation only has three
  252. commands:
  253. <ul>
  254. <li><code>cd [.|..|<i>&lt;directory&gt;</i>]</code></li>
  255. <li><code>ls [-s]</code> (<code>-s</code> orders the output by size)</li>
  256. <li><code>mkdir <i>&lt;directory&gt;</i></code></li>
  257. </ul>
  258. The program exits when the user presses the Enter key at the command prompt.
  259. </p>
  260. <p>
  261. The reader is challenged to add more functionality to the program; for
  262. instance:
  263. <ul>
  264. <li>Implement additional commands, like <code>cp</code>.</li>
  265. <li>Add handling of absolute paths.</li>
  266. <li>Use <a href="tutorial/creation.html#serialization">serialization</a>
  267. to store and retrieve the filesystem state between program runs.</li>
  268. </ul>
  269. </p>
  270. <h2><a name="example8">Example 8: hashed indices</a></h2>
  271. <p>
  272. See <a href="../example/hashed.cpp">source code</a>.
  273. </p>
  274. <p>
  275. Hashed indices can be used as an alternative to ordered indices when
  276. fast lookup is needed and sorting information is of no interest. The
  277. example features a word counter where duplicate entries are checked
  278. by means of a hashed index. Confront the word counting algorithm with
  279. that of <a href="#example5">example 5</a>.
  280. </p>
  281. <h2><a name="example9">Example 9: serialization and MRU lists</a></h2>
  282. <p>
  283. See <a href="../example/serialization.cpp">source code</a>.
  284. </p>
  285. <p>
  286. A typical application of serialization capabilities allows a program to
  287. restore the user context between executions. The example program asks
  288. the user for words and keeps a record of the ten most recently entered
  289. ones, in the current or in previous sessions. The serialized data structure,
  290. sometimes called an <i>MRU (most recently used) list</i>, has some interest
  291. on its own: an MRU list behaves as a regular FIFO queue, with the exception
  292. that, when inserting a preexistent entry, this does not appear twice, but
  293. instead the entry is moved to the front of the list. You can observe this
  294. behavior in many programs featuring a "Recent files" menu command. This
  295. data structure is implemented with <code>multi_index_container</code> by
  296. combining a sequenced index and an index of type <code>hashed_unique</code>.
  297. </p>
  298. <h2><a name="example10">Example 10: random access indices</a></h2>
  299. <p>
  300. See <a href="../example/random_access.cpp">source code</a>.
  301. </p>
  302. <p>
  303. The example resumes the text container introduced in
  304. <a href="#example5">example 5</a> and shows how substituting a random
  305. access index for a sequenced index allows for extra capabilities like
  306. efficient access by position and calculation of the offset of a given
  307. element into the container.
  308. </p>
  309. <h2><a name="example11">Example 11: index rearrangement</a></h2>
  310. <p>
  311. See <a href="../example/rearrange.cpp">source code</a>.
  312. </p>
  313. <p>
  314. There is a relatively common piece of urban lore claiming that
  315. a deck of cards must be shuffled seven times in a row to be perfectly
  316. mixed. The statement derives from the works of mathematician Persi
  317. Diaconis on <i>riffle shuffling</i>: this shuffling
  318. technique involves splitting the deck in two packets roughly the same
  319. size and then dropping the cards from both packets so that they become
  320. interleaved. It has been shown that when repeating this procedure
  321. seven times the statistical distribution of cards is reasonably
  322. close to that associated with a truly random permutation. A measure
  323. of "randomness" can be estimated by counting <i>rising sequences</i>:
  324. consider a permutation of the sequence 1,2, ... , <i>n</i>, a rising sequence
  325. is a maximal chain of consecutive elements <i>m</i>, <i>m+1</i>, ... , <i>m+r</i>
  326. such that they are arranged in ascending order. For instance, the permutation
  327. 125364789 is composed of the two rising sequences 1234 and 56789,
  328. as becomes obvious by displaying the sequence like this,
  329. <span style="vertical-align:sub">1</span><span style="vertical-align:sub">2</span><span style="vertical-align:super">5</span><span style="vertical-align:sub">3</span><span style="vertical-align:super">6</span><span style="vertical-align:sub">4</span><span style="vertical-align:super">7</span><span style="vertical-align:super">8</span><span style="vertical-align:super">9</span>.
  330. The average number of rising sequences in a random permutation of
  331. <i>n</i> elements is (<i>n</i>+1)/2: by contrast, after a single riffle
  332. shuffle of an initially sorted deck of cards, there cannot be more than
  333. two rising sequences. The average number of rising sequences approximates
  334. to (<i>n</i>+1)/2 as the number of consecutive riffle shuffles increases,
  335. with seven shuffles yielding a close result for a 52-card poker deck.
  336. Brad Mann's paper
  337. <a href="http://www.dartmouth.edu/~chance/teaching_aids/books_articles/Mann.pdf">"How
  338. many times should you shuffle a deck of cards?"</a> provides a
  339. rigorous yet very accessible treatment of this subject.
  340. </p>
  341. <p>
  342. The example program estimates the average number of rising sequences
  343. in a 52-card deck after repeated riffle shuffling as well as applying
  344. a completely random permutation. The deck is modeled by the following
  345. container:
  346. <blockquote><pre>
  347. <span class=identifier>multi_index_container</span><span class=special>&lt;</span>
  348. <span class=keyword>int</span><span class=special>,</span>
  349. <span class=identifier>indexed_by</span><span class=special>&lt;</span>
  350. <span class=identifier>random_access</span><span class=special>&lt;&gt;,</span>
  351. <span class=identifier>random_access</span><span class=special>&lt;&gt;</span>
  352. <span class=special>&gt;</span>
  353. <span class=special>&gt;</span>
  354. </pre></blockquote>
  355. where the first index stores the current arrangement of the deck, while
  356. the second index is used to remember the start position. This representation
  357. allows for an efficient implementation of a rising sequences counting
  358. algorithm in linear time.
  359. <a href="reference/rnd_indices.html#rearrange"><code>rearrange</code></a>
  360. is used to apply to the deck a shuffle performed externally on an
  361. auxiliary data structure.
  362. </p>
  363. <h2><a name="example12">Example 12: using Boost.Interprocess allocators</a></h2>
  364. <p>
  365. See <a href="../example/ip_allocator.cpp">source code</a>.
  366. </p>
  367. <p>
  368. Boost.MultiIndex supports special allocators such as those provided by
  369. <a href="../../interprocess/index.html">Boost.Interprocess</a>,
  370. which allows for <code>multi_index_container</code>s to be placed in shared
  371. memory. The example features a front-end to a small book database
  372. implemented by means of a <code>multi_index_container</code> stored
  373. in a Boost.Interprocess memory mapped file. The reader can verify that several
  374. instances of the program correctly work simultaneously and immediately see
  375. the changes to the database performed by any other instance.
  376. </p>
  377. <hr>
  378. <div class="prev_link"><a href="performance.html"><img src="prev.gif" alt="performance" border="0"><br>
  379. Performance
  380. </a></div>
  381. <div class="up_link"><a href="index.html"><img src="up.gif" alt="index" border="0"><br>
  382. Index
  383. </a></div>
  384. <div class="next_link"><a href="tests.html"><img src="next.gif" alt="tests" border="0"><br>
  385. Tests
  386. </a></div><br clear="all" style="clear: all;">
  387. <br>
  388. <p>Revised May 26th 2009</p>
  389. <p>&copy; Copyright 2003-2009 Joaqu&iacute;n M L&oacute;pez Mu&ntilde;oz.
  390. Distributed under the Boost Software
  391. License, Version 1.0. (See accompanying file <a href="../../../LICENSE_1_0.txt">
  392. LICENSE_1_0.txt</a> or copy at <a href="http://www.boost.org/LICENSE_1_0.txt">
  393. http://www.boost.org/LICENSE_1_0.txt</a>)
  394. </p>
  395. </body>
  396. </html>