tutorial.qbk 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057
  1. [/license
  2. Boost.Bimap
  3. Copyright (c) 2006-2007 Matias Capeletto
  4. Distributed under the Boost Software License, Version 1.0.
  5. (See accompanying file LICENSE_1_0.txt or copy at
  6. http://www.boost.org/LICENSE_1_0.txt)
  7. ]
  8. [/ QuickBook Document version 1.4 ]
  9. [section The tutorial]
  10. [section Roadmap]
  11. # Boost.Bimap is intuitive because it is based on the standard
  12. template library. New concepts are however presented to extend the
  13. standard maps to bidirectional maps. The first step is to gain a
  14. firm grasp of the bimap framework. The first section
  15. ([link boost_bimap.the_tutorial.discovering_the_bimap_framework Discovering the bimap framework])
  16. aims to explain this.
  17. # Boost.Bimap offers much more than just a one-to-one ordered unique
  18. bidirectional map. It is possible to control the collection type of each side
  19. of the relationship that the bimap represents, giving one-to-many
  20. containers, hashed bidirectional containers and others that may be more
  21. suitable to the the task at hand. The second section
  22. ([link boost_bimap.the_tutorial.controlling_collection_types Controlling collection types])
  23. explains how to instantiate a bimap with different collection constraints.
  24. # The section
  25. ([link boost_bimap.the_tutorial.the_collection_of_relations_type The "collection of relations" type])
  26. explains how to create new types of bidirectional maps using custom collection types.
  27. # In the section [link boost_bimap.the_tutorial.differences_with_standard_maps Differences with standard maps] we will learn about the subtle differences between a bimap map view and a standard map.
  28. # The section [link boost_bimap.the_tutorial.useful_functions Useful functions] provides information
  29. about functions of a bimap that are not found in the STL.
  30. # The types of a bimap can be tagged so that each side is accessible
  31. by something closer to the problem than left and right. This leads to
  32. more readable, self-documenting code. The fourth section
  33. ([link boost_bimap.the_tutorial.bimaps_with_user_defined_names Bimaps with user defined names]) shows
  34. how to use this feature.
  35. # The bimap mapping framework allows to disable a view of a bimap, including the standard
  36. mapping containers as a particular case. The section
  37. [link boost_bimap.the_tutorial.unconstrained_sets Unconstrained Sets] explains how they work.
  38. # The section [link boost_bimap.the_tutorial.additional_information Additional information]
  39. explains how to attach information to each relation of a bimap.
  40. # The final section
  41. ([link boost_bimap.the_tutorial.complete_instantiation_scheme Complete Instantiation Scheme])
  42. summarizes bimap instantiation and explains how change the allocator type to be used.
  43. [endsect]
  44. [section Discovering the bimap framework]
  45. [section Interpreting bidirectional maps]
  46. One way to interpret bidirectional maps is as a function between two
  47. collections of data, lets call them the left and the right collection.
  48. An element in this bimap is a relation between an element from the left
  49. collection and an element from the right collection.
  50. The types of both collections defines the bimap behaviour. We can view
  51. the stored data from the left side, as a mapping between keys from the
  52. left collection and data from the right one, or from the right side, as
  53. a mapping between keys from the right collection and data from the
  54. left collection.
  55. [endsect]
  56. [section Standard mapping framework]
  57. Relationships between data in the STL are represented by maps. A
  58. standard map is a directed relation of keys from a left collection and
  59. data from a right unconstrained collection.
  60. The following diagram shows the relationship represented and the
  61. user's viewpoint.
  62. __STANDARD_MAPPING_FRAMEWORK__
  63. The left collection type depends on the selected map type. For example if the the map type is `std::multimap` the collection type of X is a `multiset_of`.
  64. The following table shows the equivalent types for the std associative containers.
  65. [table std associative containers
  66. [[container ][left collection type ][right collection type]]
  67. [[`map` ][`set_of` ][no constraints ]]
  68. [[`multimap` ][`multiset_of` ][no constraints ]]
  69. [[`unordered_map` ][`unordered_set_of` ][no constraints ]]
  70. [[`unordered_multimap`][`unordered_multiset_of` ][no constraints ]]
  71. ]
  72. [endsect]
  73. [section Bimap mapping framework]
  74. Boost.Bimap design is based on the STL, and extends the framework in a natural way.
  75. The following diagram represents the new situation.
  76. __EXTENDED_MAPPING_FRAMEWORK__
  77. Notice that now the `std::maps` are a particular case of a Boost.Bimap
  78. container, where you can view only one side of the relationship and can
  79. control the constraints of only one of the collections. Boost.Bimap
  80. allows the user to view the relationship from three viewpoints.
  81. You can view it from one side, obtaining a `std::map` compatible
  82. container, or you can work directly with the whole relation.
  83. The next diagram shows the layout of the relation and pairs of a bimap. It is
  84. the one from the ['one minute tutorial]
  85. __RELATION_AND_PAIR__
  86. Bimap pairs are signature-compatible with standard pairs but are different
  87. from them. As you will see in other sections they can be tagged with user
  88. defined names and additional information can be attached to them. You can
  89. convert from `std::pairs` to bimap pairs directly but the reverse conversion
  90. is not provided. This mean that you can insert elements in a bimap using
  91. algorithms like `std::copy` from containers `like std::map`, or use `std::make_pair`
  92. to add new elements. However it is best to use `bm.left.insert( bm_type::left_value_type(f,s) )` instead of `bm.insert( std::make_pair(f,s) )` to avoid an extra call to the
  93. copy constructor of each type.
  94. The following code snippet shows the relation between a bimap and standard
  95. maps.
  96. [note
  97. You have to used references to views, and not directly views object.
  98. Views cannot be constructed as separate objects from the container they
  99. belong to, so the following:
  100. ``
  101. // Wrong: we forgot the & after bm_type::left_type
  102. bm_type::left_map lm = bm.left;
  103. ``
  104. does not compile, since it is trying to construct the view object `lm`.
  105. This is a common source of errors in user code.
  106. ]
  107. [@../../example/standard_map_comparison.cpp Go to source code]
  108. [import ../example/standard_map_comparison.cpp]
  109. [code_standard_map_comparison]
  110. [endsect]
  111. [endsect]
  112. [section Controlling collection types]
  113. [section Freedom of choice]
  114. As has already been said, in STL maps, you can only control the
  115. constraints from one of the collections, namely the one that you are
  116. viewing. In Boost.Bimap, you can control both and it is as easy as using the STL.
  117. __EXTENDED_MAPPING_FRAMEWORK__
  118. The idea is to use the same constraint names that are used in the
  119. standard. If you don't specify the collection type, Boost.Bimap assumes
  120. that the collection is a set. The instantiation of a bimap with custom
  121. collection types looks like this:
  122. typedef bimap< ``*CollectionType*``_of<A>, ``*CollectionType*``_of<B> > bm_type;
  123. The following is the list of all supported collection types.
  124. [table Collection of Key Types
  125. [[name ][Features ][map view type ]]
  126. [[`set_of` ][['ordered, unique]][`map` ]]
  127. [[`multiset_of` ][['ordered ]][`multimap` ]]
  128. [[`unordered_set_of` ][['hashed, unique ]][`unordered_map` ]]
  129. [[`unordered_multiset_of`][['hashed ]][`unordered_multimap` ]]
  130. [[`list_of` ][['sequenced ]][`list_map` ]]
  131. [[`vector_of` ][['random access ]][`vector_map` ]]
  132. [[`unconstrained_set_of` ][['unconstrained ]][['can not be viewed] ]]
  133. ]
  134. `list_of` and `vector_of` map views are not associated with any existing STL
  135. associative containers. They are two examples of unsorted associative
  136. containers. `unconstrained_set_of` allow the user to ignore a view. This
  137. will be explained later.
  138. __BIMAP_STRUCTURES__
  139. The selection of the collection type affects the possible operations that you
  140. can perform with each side of the bimap and the time it takes to do
  141. each. If we have:
  142. typedef bimap< ``*CollectionType*``_of<A>, ``*CollectionType*``_of<B> > bm_type;
  143. bm_type bm;
  144. The following now describes the resulting map views of the bidirectional
  145. map.
  146. * `bm.left` is signature-compatible with *LeftMapType*`<A,B>`
  147. * `bm.right` is signature-compatible with *RightMapType*`<B,A>`
  148. [endsect]
  149. [section Configuration parameters]
  150. Each collection type template has different parameters to control its
  151. behaviour. For example, in `set_of` specification, you can pass a Functor
  152. type that compares two types. All of these parameters are exactly the
  153. same as those of the standard library container, except for the
  154. allocator type. You will learn later how to change the allocator for a
  155. bimap.
  156. The following table lists the meanings of each collection type's parameters.
  157. [table
  158. [[name ][Additional Parameters]]
  159. [[`set_of<T,KeyComp>`
  160. `multiset_of<T,KeyComp>` ]
  161. [[*KeyComp ] is a Functor that compares two types using a less-than operator.
  162. By default, this is `std::less<T>`. ]]
  163. [[`unordered_set_of<T,HashFunctor,EqualKey>`
  164. `unordered_multiset_of<T,HashFunctor,EqualKey>`]
  165. [[*HashFunctor ] converts a `T` object into an `std::size_t` value. By default it is `boost::hash<T>`.
  166. [*EqualKey ] is a Functor that tests two types for equality. By default, the
  167. equality operator is `std::equal_to<T>`. ]]
  168. [[`list_of<T>` ][No additional parameters.]]
  169. [[`vector_of<T>` ][No additional parameters.]]
  170. [[`unconstrained_set_of<T>` ][No additional parameters.]]
  171. ]
  172. [endsect]
  173. [section Examples]
  174. [heading Countries Populations]
  175. We want to store countries populations.
  176. The requirements are:
  177. # Get a list of countries in decreasing order of their populations.
  178. # Given a country, get their population.
  179. Lets create the appropriate bimap.
  180. typedef bimap<
  181. unordered_set_of< std::string >,
  182. multiset_of< long, std::greater<long> >
  183. > populations_bimap;
  184. First of all countries names are unique identifiers, while two countries
  185. may have the same population. This is why we choose *multi*`set_of` for
  186. populations.
  187. Using a `multiset_of` for population allow us to iterate over the data.
  188. Since listing countries ordered by their names is not a requisite, we can
  189. use an `unordered_set_of` that allows constant order look up.
  190. And now lets use it in a complete example
  191. [@../../example/population_bimap.cpp Go to source code]
  192. [import ../example/population_bimap.cpp]
  193. [code_population_bimap]
  194. [heading Repetitions counter]
  195. We want to count the repetitions for each word in a text and print them
  196. in order of appearance.
  197. [@../../example/repetitions_counter.cpp Go to source code]
  198. [import ../example/repetitions_counter.cpp]
  199. [code_repetitions_counter]
  200. [endsect]
  201. [endsect]
  202. [section The collection of relations type]
  203. [section A new point of view]
  204. Being able to change the collection type of the bimap relation view is another
  205. very important feature. Remember that this view allows the user to see
  206. the container as a group of the stored relations. This view has set
  207. semantics instead of map semantics.
  208. __COLLECTION_TYPE_OF_RELATION__
  209. By default, Boost.Bimap will base the collection type of the relation on the
  210. type of the left collection. If the left collection type is a set, then the collection
  211. type of the relation will be a set with the same order as the left view.
  212. In general, Boost.Bimap users will base the collection type of a relation on
  213. the type of the collection on one of the two sides. However there are times
  214. where it is useful to give this collection other constraints or simply to order
  215. it differently. The user is allowed to choose between:
  216. * left_based
  217. * right_based
  218. * set_of_relation<>
  219. * multiset_of_relation<>
  220. * unordered_set_of_relation<>
  221. * unordered_multiset_of_relation<>
  222. * list_of_relation
  223. * vector_of_relation
  224. * unconstrained_set_of_relation
  225. [tip
  226. The first two options and the last produce faster bimaps, so prefer
  227. these where possible.
  228. ]
  229. __MORE_BIMAP_STRUCTURES__
  230. The collection type of relation can be used to create powerful containers. For
  231. example, if you need to maximize search speed, then the best
  232. bidirectional map possible is one that relates elements from an
  233. `unordered_set` to another `unordered_set`. The problem is that this
  234. container cannot be iterated. If you need to know the list of relations
  235. inside the container, you need another collection type of relation. In this
  236. case, a `list_of_relation` is a good choice. The resulting container
  237. trades insertion and deletion time against fast search capabilities and
  238. the possibility of bidirectional iteration.
  239. [@../../example/mighty_bimap.cpp Go to source code]
  240. [code_mighty_bimap]
  241. [endsect]
  242. [section Configuration parameters]
  243. Each collection type of relation has different parameters to control its
  244. behaviour. For example, in the `set_of_relation` specification, you can
  245. pass a Functor type that compares two types. All of the parameters are
  246. exactly as in the standard library containers, except for the type,
  247. which is set to the bimap relation and the allocator type. To help users
  248. in the creation of each functor, the collection type of relation templates
  249. takes an mpl lambda expression where the relation type will be evaluated
  250. later. A placeholder named `_relation` is available to bimap users.
  251. The following table lists the meaning of the parameters for each collection type of
  252. relations.
  253. [table
  254. [[name ][Additional Parameters]]
  255. [[`left_based` ][Not a template.]]
  256. [[`right_based` ][Not a template.]]
  257. [[`set_of_relation<KeyComp>`
  258. `multiset_of_relation<KeyComp>` ]
  259. [[*KeyComp ] is a Functor that compares two types using less than. By
  260. default, the less-than operator is `std::less<_relation>`. ]]
  261. [[`unordered_set_of_relation<HashFunctor,EqualKey>`
  262. `unordered_multiset_of_relation<HashFunctor,EqualKey>`]
  263. [[*HashFunctor ] converts the `relation` into an `std::size_t` value. By default it is `boost::hash<_relation>`.
  264. [*EqualKey ] is a Functor that tests two relations for equality. By default,
  265. the equality operator is `std::equal_to<_relation>`. ]]
  266. [[`list_of_relation` ][Not a template.]]
  267. [[`vector_of_relation` ][Not a template.]]
  268. [[`unconstrained_set_of_relation` ][Not a template.]]
  269. ]
  270. [endsect]
  271. [section Examples]
  272. Consider this example:
  273. template< class Rel >
  274. struct RelOrder
  275. {
  276. bool operator()(Rel ra, Rel rb) const
  277. {
  278. return (ra.left+ra.right) < (rb.left+rb.right);
  279. }
  280. };
  281. typedef bimap
  282. <
  283. multiset_of< int >,
  284. multiset_of< int >,
  285. set_of_relation< RelOrder<_relation> >
  286. > bimap_type;
  287. Here the bimap relation view is ordered using the information of
  288. both sides. This container will only allow unique relations because
  289. `set_of_relation` has been used but the elements in each side of the
  290. bimap can be repeated.
  291. struct name {};
  292. struct phone_number {};
  293. typedef bimap
  294. <
  295. tagged< unordered_multiset_of< string >, name >,
  296. tagged< unordered_set_of < int >, phone_number >,
  297. set_of_relation<>
  298. > bimap_type;
  299. In this other case the bimap will relate names to phone numbers.
  300. Names can be repeated and phone numbers are unique. You can perform
  301. quick searches by name or phone number and the container can be viewed
  302. ordered using the relation view.
  303. [endsect]
  304. [endsect]
  305. [section Differences with standard maps]
  306. [section Insertion]
  307. Remember that a map can be interpreted as a relation between two collections.
  308. In bimaps we have the freedom to change both collection types, imposing
  309. constrains in each of them. Some insertions that we give for granted to
  310. success in standard maps fails with bimaps.
  311. For example:
  312. bimap<int,std::string> bm;
  313. bm.left.insert(1,"orange");
  314. bm.left.insert(2,"orange"); // No effect! returns make_pair(iter,false)
  315. The insertion will only succeed if it is allowed by all views of the `bimap`.
  316. In the next snippet we define the right collection as a multiset, when we
  317. try to insert the same two elements the second insertion is allowed by the
  318. left map view because both values are different and it is allowed by the
  319. right map view because it is a non-unique collection type.
  320. bimap<int, multiset_of<std::string> > bm;
  321. bm.left.insert(1,"orange");
  322. bm.left.insert(2,"orange"); // Insertion succeed!
  323. If we use a custom collection of relation type, the insertion has to be
  324. allowed by it too.
  325. [endsect]
  326. [section iterator::value_type]
  327. The relations stored in the Bimap will not be in most cases modifiable
  328. directly by iterators because both sides are used as keys of
  329. ['key-based] sets. When a `bimap<A,B>` left view iterator is dereferenced
  330. the return type is ['signature-compatible] with a
  331. `std::pair< const A, const B >`.
  332. However there are some collection types that are not ['key_based], for example
  333. list_of. If a Bimap uses one of these collection types there is no problem with
  334. modifying the data of that side. The following code is valid:
  335. typedef bimap< int, list_of< std::string > > bm_type;
  336. bm_type bm;
  337. bm.insert( bm_type::relation( 1, "one" ) );
  338. ...
  339. bm.left.find(1)->second = "1"; // Valid
  340. In this case, when the iterator is dereferenced the return type is
  341. ['signature-compatible] with a `std::pair<const int, std::string>`.
  342. The following table shows the constness of the dereferenced data of each
  343. collection type of:
  344. [table
  345. [[Side collection type ][Dereferenced data]]
  346. [[`set_of` ][['constant]]]
  347. [[`multiset_of` ][['constant]]]
  348. [[`unordered_set_of` ][['constant]]]
  349. [[`unordered_multiset_of`][['constant]]]
  350. [[`list_of` ][['mutable] ]]
  351. [[`vector_of` ][['mutable] ]]
  352. [[`unconstrained_set_of` ][['mutable] ]]
  353. ]
  354. Here are some examples. When dereferenced the iterators returns a type that
  355. is ['signature-compatible] with these types.
  356. [table
  357. [[Bimap type ][Signature-compatible types]]
  358. [[`bimap<A,B>`][
  359. `iterator ` *->* `relation<const A,const B>`
  360. `left_iterator ` *->* `pair<const A,const B>`
  361. `right_iterator` *->* `pair<const B,const A>`
  362. ]]
  363. [[`bimap<multiset_of<A>,unordered_set_of<B> >`][
  364. `iterator ` *->* `relation<const A,const B>`
  365. `left_iterator ` *->* `pair<const A,const B>`
  366. `right_iterator` *->* `pair<const B,const A>`
  367. ]]
  368. [[`bimap<set_of<A>,list_of<B> >`][
  369. `iterator ` *->* `relation<const A,B>`
  370. `left_iterator ` *->* `pair<const A,B>`
  371. `right_iterator` *->* `pair<B,const A>`
  372. ]]
  373. [[`bimap<vector_of<A>,set_of<B> >`][
  374. `iterator ` *->* `relation<A,const B>`
  375. `left_iterator ` *->* `pair<A,const B>`
  376. `right_iterator` *->* `pair<const B,A>`
  377. ]]
  378. [[`bimap<list_of<A>,unconstrained_set_of<B> >`][
  379. `iterator ` *->* `relation<A,B>`
  380. `left_iterator ` *->* `pair<A,B>`
  381. `right_iterator` *->* `pair<B,A>`
  382. ]]
  383. ]
  384. [endsect]
  385. [section operator\[\] and at()]
  386. `set_of` and `unordered_set_of` map views overload `operator[]` to retrieve the
  387. associated data of a given key only when the other collection type is a
  388. mutable one. In these cases it works in the same way as the standard.
  389. bimap< unorderd_set_of< std::string>, list_of<int> > bm;
  390. bm.left["one"] = 1; // Ok
  391. The standard defines an access function for `map` and `unordered_map`:
  392. const data_type & at(const key_type & k) const;
  393. data_type & at(const key_type & k);
  394. These functions look for a key and returns the associated data value, but
  395. throws a `std::out_of_range` exception if the key is not found.
  396. In bimaps the constant version of these functions is given for `set_of` and
  397. `unorderd_set_of` map views independently of the other collection type.
  398. The mutable version is only provided when the other collection type is
  399. mutable.
  400. The following examples shows the behaviour of `at(key)`
  401. [@../../example/at_function_examples.cpp Go to source code]
  402. [import ../example/at_function_examples.cpp]
  403. [code_at_function_first]
  404. [code_at_function_second]
  405. [/
  406. `set_of` and `unordered_set_of` views overload `operator[]` to retrieve the
  407. associated data of a given key.
  408. The symmetry of bimap imposes some constraints on `operator[]` that are
  409. not found in `std::map` or `std::unordered_map`. If other views are unique,
  410. `bimap::duplicate_value` is thrown whenever an assignment is attempted to
  411. a value that is already a key in these views. As for
  412. `bimap::value_not_found`, this exception is thrown while trying to access
  413. a non-existent key: this behaviour differs from the standard containers,
  414. which automatically assigns a default value to non-existent keys referred to
  415. by `operator[]`.
  416. const data_type & operator[](const typename key_type & k) const;
  417. [: Returns the `data_type` reference that is associated with `k`, or
  418. throws `bimap::value_not_found` if such an element does not exist.
  419. ]
  420. ``['-unspecified data_type proxy-]`` operator[](const typename key_type & k);
  421. [: Returns a proxy to a `data_type` associated with `k` and the
  422. bimap. The proxy behaves as a reference to the `data_type` object. If this
  423. proxy is read and `k` was not in the bimap, the bimap::value_not_found is
  424. thrown. If it is written then `bimap::duplicate_value` is thrown if the
  425. assignment is not allowed by one of the other views of the `bimap`.
  426. ]
  427. The following example shows the behaviour of `operator[]`
  428. bimap<int,std::string> bm;
  429. bm.left[1] = "one"; // Ok
  430. bm.right["two"] = 2; // Ok
  431. if( bm.left[3] == "three" ) // throws bimap::value_not_found
  432. {
  433. ...
  434. }
  435. bm.left[3] = "one"; // throws bimap::duplicate_value
  436. ]
  437. [endsect]
  438. [section Complexity of operations]
  439. The complexity of some operations is different in bimaps. Read
  440. [link complexity_signature_explanation the reference] to find the
  441. complexity of each function.
  442. [endsect]
  443. [endsect]
  444. [section Useful functions]
  445. [section Projection of iterators]
  446. Iterators can be projected to any of the three views of the bimap.
  447. A bimap provides three member functions to cope with projection: `project_left`,
  448. `project_right` and `project_up`, with projects iterators to the ['left map view],
  449. the ['right map view] and the ['collection of relations view]. These functions
  450. take any iterator from the bimap and retrieve an iterator over the projected view
  451. pointing to the same element.
  452. [import ../example/projection.cpp]
  453. Here is an example that uses projection:
  454. [@../../example/projection.cpp Go to source code]
  455. [code_projection_years]
  456. [endsect]
  457. [section replace and modify]
  458. [import ../example/tutorial_modify_and_replace.cpp]
  459. These functions are members of the views of a bimap that are not founded in
  460. their standard counterparts.
  461. The `replace` family member functions performs in-place replacement of a given
  462. element as the following example shows:
  463. [@../../example/tutorial_modify_and_replace.cpp Go to source code]
  464. [code_tutorial_replace]
  465. `replace` functions performs this substitution in such a manner that:
  466. * The complexity is constant time if the changed element retains its original order
  467. with respect to all views; it is logarithmic otherwise.
  468. * Iterator and reference validity are preserved.
  469. * The operation is strongly exception-safe, i.e. the `bimap` remains unchanged if
  470. some exception (originated by the system or the user's data types) is thrown.
  471. `replace` functions are powerful operations not provided by standard STL containers,
  472. and one that is specially handy when strong exception-safety is required.
  473. The observant reader might have noticed that the convenience of replace comes at a
  474. cost: namely the whole element has to be copied ['twice] to do the updating (when
  475. retrieving it and inside `replace`). If elements are expensive to copy, this may
  476. be quite a computational cost for the modification of just a tiny part of the
  477. object. To cope with this situation, Boost.Bimap provides an alternative
  478. updating mechanism: `modify` functions.
  479. `modify` functions accepts a functor (or pointer to function) taking a reference
  480. to the data to be changed, thus eliminating the need for spurious copies. Like
  481. `replace` functions, `modify` functions does preserve the internal orderings of
  482. all the indices of the `bimap`. However, the semantics of modify functions are not
  483. entirely equivalent to replace functions. Consider what happens if a collision occurs
  484. as a result of modifying the element, i.e. the modified element clashes with another
  485. with respect to some unique view. In the case of `replace` functions, the original
  486. value is kept and the method returns without altering the container, but `modify`
  487. functions cannot afford such an approach, since the modifying functor leaves no
  488. trace of the previous value of the element. Integrity constraints thus lead to the
  489. following policy: when a collision happens in the process of calling a modify functions,
  490. the element is erased and the method returns false. This difference in behavior
  491. between `replace` and `modify` functions has to be considered by the programmer on
  492. a case-by-case basis.
  493. Boost.Bimap defines new placeholders named `_key` and `_data` to allow a sounder solution.
  494. You have to include `<boost/bimap/support/lambda.hpp>` to use them.
  495. [/
  496. Boost.Bimap defines new placeholders to allow a sounder solution. For
  497. pairs, two new placeholders are instantiated: `_first` and `_second`, and
  498. for a relation, two more complete the set: `_left` and `_right`.
  499. ]
  500. [@../../example/tutorial_modify_and_replace.cpp Go to source code]
  501. [code_tutorial_modify]
  502. [endsect]
  503. [section Retrieval of ranges]
  504. [import ../example/tutorial_range.cpp]
  505. Standard `lower_bound` and `upper_bound` functions can be used to lookup for
  506. all the elements in a given range.
  507. Suppose we want to retrieve the elements from a `bimap<int,std::string>`
  508. where the left value is in the range `[20,50]`
  509. [code_tutorial_range_standard_way]
  510. Subtle changes to the code are required when strict inequalities are considered.
  511. To retrieve the elements greater than 20 and less than 50, the code has to be
  512. rewritten as
  513. [code_tutorial_range_standard_way_subtle_changes]
  514. To add to this complexity, the careful programmer has to take into account that
  515. the lower and upper bounds of the interval searched be compatible: for instance,
  516. if the lower bound is 50 and the upper bound is 20, the iterators `iter_first` and
  517. `iter_second` produced by the code above will be in reverse order, with possibly
  518. catastrophic results if a traversal from `iter_first` to `iter_second` is tried.
  519. All these details make range searching a tedious and error prone task.
  520. The range member function, often in combination with lambda expressions,
  521. can greatly help alleviate this situation:
  522. [code_tutorial_range]
  523. `range` simply accepts predicates specifying the lower and upper bounds of
  524. the interval searched. Please consult the reference for a detailed explanation
  525. of the permissible predicates passed to range.
  526. One or both bounds can be omitted with the special unbounded marker:
  527. [code_tutorial_range_unbounded]
  528. [@../../example/tutorial_range.cpp Go to source code]
  529. [endsect]
  530. [endsect]
  531. [section Bimaps with user defined names]
  532. [import ../example/user_defined_names.cpp]
  533. In the following example, the library user inserted comments to guide
  534. future programmers:
  535. [@../../example/user_defined_names.cpp Go to source code]
  536. [code_user_defined_names_untagged_version]
  537. In Boost.Bimap there is a better way to document the code and
  538. in the meantime helping you to write more maintainable and readable code.
  539. You can tag the two collections of the bimap so they can be
  540. accessed by more descriptive names.
  541. __TAGGED__
  542. A tagged type is a type that has been labelled using a tag. A tag is any
  543. valid C++ type. In a bimap, the types are always tagged. If you do not
  544. specify your own tag, the container uses `member_at::left` and
  545. `member_at::right` to tag the left and right sides respectively. In order
  546. to specify a custom tag, the type of each side has to be tagged.
  547. Tagging a type is very simple:
  548. typedef tagged< int, a_tag > tagged_int;
  549. Now we can rewrite the example:
  550. [@../../example/user_defined_names.cpp Go to source code]
  551. [code_user_defined_names_tagged_version]
  552. Here is a list of common structures in both tagged and untagged versions.
  553. Remember that when the bimap has user defined tags you can still use
  554. the untagged version structures.
  555. struct Left {};
  556. struct Right {};
  557. typedef bimap<
  558. multiset_of< tagged< int, Left > >,
  559. unordered_set_of< tagged< int, Right > >
  560. > bm_type;
  561. bm_type bm;
  562. //...
  563. bm_type::iterator iter = bm.begin();
  564. bm_type::left_iterator left_iter = bm.left.begin();
  565. bm_type::right_iterator right_iter = bm.right.begin();
  566. [table Equivalence of expresions using user defined names
  567. [[Untagged version] [Tagged version] ]
  568. [[`bm.left`] [`bm.by<Left>()`] ]
  569. [[`bm.right`] [`bm.by<Right>()`] ]
  570. [[`bm_type::left_map`] [`bm::map_by<Left>::type`] ]
  571. [[`bm_type::right_value_type`] [`bm::map_by<Right>::value_type`] ]
  572. [[`bm_type::left_iterator`] [`bm::map_by<Left>::iterator`] ]
  573. [[`bm_type::right_const_iterator`][`bm::map_by<Right>::const_iterator`]]
  574. [[`iter->left`] [`iter->get<Left>()`] ]
  575. [[`iter->right`] [`iter->get<Right>()`] ]
  576. [[`left_iter->first`] [`left_iter->get<Left>()`] ]
  577. [[`left_iter->second`] [`left_iter->get<Right>()`] ]
  578. [[`right_iter->first`] [`right_iter->get<Right>()`] ]
  579. [[`right_iter->second`] [`right_iter->get<Left>()`] ]
  580. [[`bm.project_left(iter)`] [`bm.project<Left>(iter)`] ]
  581. [[`bm.project_right(iter)`] [`bm.project<Right>(iter)`] ]
  582. ]
  583. [endsect]
  584. [section Unconstrained Sets]
  585. Unconstrained sets allow the user to disable one of the views of a
  586. bimap. Doing so makes the bimap operations execute faster and reduces
  587. memory consumption. This completes the bidirectional mapping framework
  588. by including unidirectional mappings as a particular case.
  589. Unconstrained sets are useful for the following reasons:
  590. * A bimap type has stronger guarantees than its standard equivalent,
  591. and includes some useful functions (replace, modify) that the standard
  592. does not have.
  593. * You can view the mapping as a collection of relations.
  594. * Using this kind of map makes the code very extensible. If, at any
  595. moment of the development, the need to perform searches from the right
  596. side of the mapping arises, the only necessary change is to the `typedef`.
  597. [import ../example/unconstrained_collection.cpp]
  598. Given this bimap instance,
  599. [code_unconstrained_collection_bimap]
  600. or this standard map one
  601. [code_unconstrained_collection_map]
  602. The following code snippet is valid
  603. [code_unconstrained_collection_common]
  604. But using a bimap has some benefits
  605. [code_unconstrained_collection_only_for_bimap]
  606. [@../../example/unconstrained_collection.cpp Go to source code]
  607. [endsect]
  608. [section Additional information]
  609. [import ../example/tutorial_info_hook.cpp]
  610. Bidirectional maps may have associated information about each relation.
  611. Suppose we want to represent a books and author bidirectional map.
  612. [code_tutorial_info_hook_nothing]
  613. Suppose now that we want to store abstract of each book.
  614. We have two options:
  615. # Books name are unique identifiers, so we can create a separate
  616. `std::map< string, string >` that relates books names with abstracts.
  617. # We can use __BOOST_MULTI_INDEX__ for the new beast.
  618. Option 1 is the wrong approach, if we go this path we lost what bimap has
  619. won us. We now have to maintain the logic of two interdependent containers,
  620. there is an extra string stored for each book name, and the performance will
  621. be worse. This is far away from being a good solution.
  622. Option 2 is correct. We start thinking books as entries in a table. So it
  623. makes sense to start using Boost.MultiIndex. We can then add the year
  624. of publication, the price, etc... and we can index this new items too. So
  625. Boost.MultiIndex is a sound solution for our problem.
  626. The thing is that there are cases where we want to maintain bimap
  627. semantics (use `at()` to find an author given a book name and the other way
  628. around) and add information about the relations that we are sure we will not
  629. want to index later (like the abstracts). Option 1 is not possible, option 2
  630. neither.
  631. Boost.Bimap provides support for this kind of situations by means of
  632. an embedded information member.
  633. You can pass an extra parameter to a bimap: `with_info< InfoType >`
  634. and an `info` member of type `InfoType` will appear in the relation and bimap
  635. pairs.
  636. __RELATION_AND_PAIR_WITH_INFO__
  637. Relations and bimap pairs constructors will take an extra argument.
  638. If only two arguments are used, the information will be initialized with
  639. their default constructor.
  640. [code_tutorial_info_hook_first]
  641. Contrary to the two key types, the information will be mutable using iterators.
  642. [code_tutorial_info_hook_mutable]
  643. A new function is included in ['unique] map views: `info_at(key)`, that mimics the
  644. standard `at(key)` function but returned the associated information instead of
  645. the data.
  646. [code_tutorial_info_hook_info_at]
  647. The info member can be tagged just as the left or the right member. The following
  648. is a rewrite of the above example using user defined names:
  649. [code_tutorial_info_hook_tagged_info]
  650. [@../../example/tutorial_info_hook.cpp Go to source code]
  651. [endsect]
  652. [section Complete instantiation scheme]
  653. To summarize, this is the complete instantiation scheme.
  654. typedef bimap
  655. <
  656. LeftCollectionType, RightCollectionType
  657. [ , SetTypeOfRelation ] // Default to left_based
  658. [ , with_info< Info > ] // Default to no info
  659. [ , Allocator ] // Default to std::allocator<>
  660. > bm;
  661. `{Side}CollectionType` can directly be a type. This defaults to
  662. `set_of<Type>`, or can be a `{CollectionType}_of<Type>` specification.
  663. Additionally, the type of this two parameters can be tagged to specify
  664. user defined names instead of the usual `member_at::-Side-` tags.
  665. The possible way to use the first parameter are:
  666. bimap< Type, R >
  667. * Left type: `Type`
  668. * Left collection type: `set_of< Type >`
  669. * Left tag: `member_at::left`
  670. bimap< {CollectionType}_of< Type >, R >
  671. * Left type: `Type`
  672. * Left collection type: `{CollectionType}_of< LeftType >`
  673. * Left tag: `member_at::left`
  674. bimap< tagged< Type, Tag >, R >
  675. * Left type: `Type`
  676. * Left collection type: `set_of< LeftType >`
  677. * Left tag: `Tag`
  678. bimap< {CollectionType}_of< tagged< Type, Tag > >, R >
  679. * Left type: `Type`
  680. * Left collection type: `{CollectionType}_of< LeftType >`
  681. * Left tag: `Tag`
  682. The same options are available for the second parameter.
  683. The last three parameters are used to specify the collection type of the relation,
  684. the information member and the allocator type.
  685. If you want to specify a custom allocator type while relying on the default
  686. value of CollectionTypeOfRelation, you can do so by simply writing
  687. `bimap<LeftKeyType, RightKeyType, Allocator>`. Boost.Bimap's internal
  688. machinery detects that the third parameter in this case does not refer
  689. to the relation type but rather to an allocator.
  690. The following are the possible ways of instantiating the last three parameters
  691. of a bimap. You can ignore some of the parameter but the order must be respected.
  692. bimap< L, R >
  693. * set_of_relation_type: based on the left key type
  694. * info: no info
  695. * allocator: std::allocator
  696. bimap< L, R ,SetOfRelationType>
  697. * set_of_relation_type: SetOfRelationType
  698. * info: no info
  699. * allocator: std::allocator
  700. bimap< L, R , SetOfRelationType, with_info<Info> >
  701. * set_of_relation_type: SetOfRelationType
  702. * info: Info
  703. * allocator: std::allocator
  704. bimap< L, R , SetOfRelationType, with_info<Info>, Allocator>
  705. * set_of_relation_type: SetOfRelationType
  706. * info: Info
  707. * allocator: Allocator
  708. bimap< L, R , SetOfRelationType, Allocator>
  709. * set_of_relation_type: SetOfRelationType
  710. * info: no info
  711. * allocator: Allocator
  712. bimap< L, R , with_info<Info> >
  713. * set_of_relation_type: based on the left key type
  714. * info: Info
  715. * allocator: std::allocator
  716. bimap< L, R , with_info<Info>, Allocator>
  717. * set_of_relation_type: based on the left key type
  718. * allocator: Allocator
  719. bimap< L, R , Allocator>
  720. * set_of_relation_type: based on the left key type
  721. * info: no info
  722. * allocator: Allocator
  723. [endsect]
  724. [endsect]