]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/libstdc++-v3/contrib/libstdc++-v3-4.4/doc/xml/manual/containers.xml
update
[l4.git] / l4 / pkg / libstdc++-v3 / contrib / libstdc++-v3-4.4 / doc / xml / manual / containers.xml
1 <?xml version='1.0'?>
2 <!DOCTYPE part PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" 
3  "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" 
4 [ ]>
5
6 <part id="manual.containers" xreflabel="Containers">
7 <?dbhtml filename="containers.html"?>
8  
9 <partinfo>
10   <keywordset>
11     <keyword>
12       ISO C++
13     </keyword>
14     <keyword>
15       library
16     </keyword>
17   </keywordset>
18 </partinfo>
19
20 <title>
21   Containers
22   <indexterm><primary>Containers</primary></indexterm>
23 </title>
24
25 <!-- Chapter 01 : Sequences -->
26 <chapter id="manual.containers.sequences" xreflabel="Sequences">
27 <?dbhtml filename="sequences.html"?>
28   <title>Sequences</title>
29
30 <sect1 id="containers.sequences.list" xreflabel="list">
31 <?dbhtml filename="list.html"?>
32   <title>list</title>
33   <sect2 id="sequences.list.size" xreflabel="list::size() is O(n)">
34     <title>list::size() is O(n)</title>
35    <para>
36      Yes it is, and that's okay.  This is a decision that we preserved
37      when we imported SGI's STL implementation.  The following is
38      quoted from <ulink
39      url="http://www.sgi.com/tech/stl/FAQ.html">their FAQ</ulink>:
40    </para>
41    <blockquote>
42      <para>
43        The size() member function, for list and slist, takes time
44        proportional to the number of elements in the list.  This was a
45        deliberate tradeoff.  The only way to get a constant-time
46        size() for linked lists would be to maintain an extra member
47        variable containing the list's size.  This would require taking
48        extra time to update that variable (it would make splice() a
49        linear time operation, for example), and it would also make the
50        list larger.  Many list algorithms don't require that extra
51        word (algorithms that do require it might do better with
52        vectors than with lists), and, when it is necessary to maintain
53        an explicit size count, it's something that users can do
54        themselves.
55      </para>
56      <para>
57        This choice is permitted by the C++ standard. The standard says
58        that size() <quote>should</quote> be constant time, and
59        <quote>should</quote> does not mean the same thing as
60        <quote>shall</quote>.  This is the officially recommended ISO
61        wording for saying that an implementation is supposed to do
62        something unless there is a good reason not to.
63       </para>
64       <para>
65         One implication of linear time size(): you should never write
66       </para>
67          <programlisting>
68          if (L.size() == 0)
69              ...
70          </programlisting>
71
72          <para>
73          Instead, you should write
74          </para>
75
76          <programlisting>
77          if (L.empty())
78              ...
79          </programlisting>
80    </blockquote>
81   </sect2>
82 </sect1>
83
84 <sect1 id="containers.sequences.vector" xreflabel="vector">
85 <?dbhtml filename="vector.html"?>
86   <title>vector</title>
87   <para>
88   </para>
89   <sect2 id="sequences.vector.management" xreflabel="Space Overhead Management">
90     <title>Space Overhead Management</title>
91    <para>
92      In <ulink
93      url="http://gcc.gnu.org/ml/libstdc++/2002-04/msg00105.html">this
94      message to the list</ulink>, Daniel Kostecky announced work on an
95      alternate form of <code>std::vector</code> that would support
96      hints on the number of elements to be over-allocated.  The design
97      was also described, along with possible implementation choices.
98    </para>
99    <para>
100      The first two alpha releases were announced <ulink
101      url="http://gcc.gnu.org/ml/libstdc++/2002-07/msg00048.html">here</ulink>
102      and <ulink
103      url="http://gcc.gnu.org/ml/libstdc++/2002-07/msg00111.html">here</ulink>.
104      The releases themselves are available at
105       <ulink url="http://www.kotelna.sk/dk/sw/caphint/">
106       http://www.kotelna.sk/dk/sw/caphint/</ulink>.
107    </para>
108
109   </sect2></sect1>
110 </chapter>
111
112 <!-- Chapter 02 : Associative -->
113 <chapter id="manual.containers.associative" xreflabel="Associative">
114 <?dbhtml filename="associative.html"?>
115   <title>Associative</title>
116
117   <sect1 id="containers.associative.insert_hints" xreflabel="Insertion Hints">
118     <title>Insertion Hints</title>
119    <para>
120      Section [23.1.2], Table 69, of the C++ standard lists this
121      function for all of the associative containers (map, set, etc):
122    </para>
123    <programlisting>
124       a.insert(p,t);
125    </programlisting>
126    <para>
127      where 'p' is an iterator into the container 'a', and 't' is the
128      item to insert.  The standard says that <quote><code>t</code> is
129      inserted as close as possible to the position just prior to
130      <code>p</code>.</quote> (Library DR #233 addresses this topic,
131      referring to <ulink
132      url='http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1780.html'>N1780</ulink>.
133      Since version 4.2 GCC implements the resolution to DR 233, so
134      that insertions happen as close as possible to the hint. For
135      earlier releases the hint was only used as described below.
136    </para>
137    <para>
138      Here we'll describe how the hinting works in the libstdc++
139      implementation, and what you need to do in order to take
140      advantage of it.  (Insertions can change from logarithmic
141      complexity to amortized constant time, if the hint is properly
142      used.)  Also, since the current implementation is based on the
143      SGI STL one, these points may hold true for other library
144      implementations also, since the HP/SGI code is used in a lot of
145      places.
146    </para>
147    <para>
148      In the following text, the phrases <emphasis>greater
149      than</emphasis> and <emphasis>less than</emphasis> refer to the
150      results of the strict weak ordering imposed on the container by
151      its comparison object, which defaults to (basically)
152      <quote>&lt;</quote>.  Using those phrases is semantically sloppy,
153      but I didn't want to get bogged down in syntax.  I assume that if
154      you are intelligent enough to use your own comparison objects,
155      you are also intelligent enough to assign <quote>greater</quote>
156      and <quote>lesser</quote> their new meanings in the next
157      paragraph.  *grin*
158    </para>
159    <para>
160      If the <code>hint</code> parameter ('p' above) is equivalent to:
161    </para>
162      <itemizedlist>
163       <listitem>
164         <para>
165           <code>begin()</code>, then the item being inserted should
166           have a key less than all the other keys in the container.
167           The item will be inserted at the beginning of the container,
168           becoming the new entry at <code>begin()</code>.
169       </para>
170       </listitem>
171       <listitem>
172         <para>
173           <code>end()</code>, then the item being inserted should have
174           a key greater than all the other keys in the container.  The
175           item will be inserted at the end of the container, becoming
176           the new entry at <code>end()</code>.  
177       </para>
178       </listitem>
179       <listitem>
180         <para>
181           neither <code>begin()</code> nor <code>end()</code>, then:
182           Let <code>h</code> be the entry in the container pointed to
183           by <code>hint</code>, that is, <code>h = *hint</code>.  Then
184           the item being inserted should have a key less than that of
185           <code>h</code>, and greater than that of the item preceding
186           <code>h</code>.  The new item will be inserted between
187           <code>h</code> and <code>h</code>'s predecessor.
188           </para>
189       </listitem>
190      </itemizedlist>
191    <para>
192      For <code>multimap</code> and <code>multiset</code>, the
193      restrictions are slightly looser: <quote>greater than</quote>
194      should be replaced by <quote>not less than</quote>and <quote>less
195      than</quote> should be replaced by <quote>not greater
196      than.</quote> (Why not replace greater with
197      greater-than-or-equal-to?  You probably could in your head, but
198      the mathematicians will tell you that it isn't the same thing.)
199    </para>
200    <para>
201      If the conditions are not met, then the hint is not used, and the
202      insertion proceeds as if you had called <code> a.insert(t)
203      </code> instead.  (<emphasis>Note </emphasis> that GCC releases
204      prior to 3.0.2 had a bug in the case with <code>hint ==
205      begin()</code> for the <code>map</code> and <code>set</code>
206      classes.  You should not use a hint argument in those releases.)
207    </para>
208    <para>
209      This behavior goes well with other containers'
210      <code>insert()</code> functions which take an iterator: if used,
211      the new item will be inserted before the iterator passed as an
212      argument, same as the other containers.
213    </para>
214    <para>
215      <emphasis>Note </emphasis> also that the hint in this
216      implementation is a one-shot.  The older insertion-with-hint
217      routines check the immediately surrounding entries to ensure that
218      the new item would in fact belong there.  If the hint does not
219      point to the correct place, then no further local searching is
220      done; the search begins from scratch in logarithmic time.
221    </para>
222   </sect1>
223
224
225   <sect1 id="containers.associative.bitset" xreflabel="bitset">
226     <?dbhtml filename="bitset.html"?>
227     <title>bitset</title>
228     <sect2 id="associative.bitset.size_variable" xreflabel="Variable">
229       <title>Size Variable</title>
230       <para>
231         No, you cannot write code of the form
232       </para>
233       <!-- Careful, the leading spaces in PRE show up directly. -->
234    <programlisting>
235       #include &lt;bitset&gt;
236
237       void foo (size_t n)
238       {
239           std::bitset&lt;n&gt;   bits;
240           ....
241       } 
242    </programlisting>
243    <para>
244      because <code>n</code> must be known at compile time.  Your
245      compiler is correct; it is not a bug.  That's the way templates
246      work.  (Yes, it <emphasis>is</emphasis> a feature.)
247    </para>
248    <para>
249      There are a couple of ways to handle this kind of thing.  Please
250      consider all of them before passing judgement.  They include, in
251      no particular order:
252    </para>
253       <itemizedlist>
254         <listitem><para>A very large N in <code>bitset&lt;N&gt;</code>.</para></listitem>
255         <listitem><para>A container&lt;bool&gt;.</para></listitem>
256         <listitem><para>Extremely weird solutions.</para></listitem>
257       </itemizedlist>
258    <para>
259      <emphasis>A very large N in
260      <code>bitset&lt;N&gt;</code>.&nbsp;&nbsp;</emphasis> It has been
261      pointed out a few times in newsgroups that N bits only takes up
262      (N/8) bytes on most systems, and division by a factor of eight is
263      pretty impressive when speaking of memory.  Half a megabyte given
264      over to a bitset (recall that there is zero space overhead for
265      housekeeping info; it is known at compile time exactly how large
266      the set is) will hold over four million bits.  If you're using
267      those bits as status flags (e.g.,
268      <quote>changed</quote>/<quote>unchanged</quote> flags), that's a
269      <emphasis>lot</emphasis> of state.
270    </para>
271    <para>
272      You can then keep track of the <quote>maximum bit used</quote>
273      during some testing runs on representative data, make note of how
274      many of those bits really need to be there, and then reduce N to
275      a smaller number.  Leave some extra space, of course.  (If you
276      plan to write code like the incorrect example above, where the
277      bitset is a local variable, then you may have to talk your
278      compiler into allowing that much stack space; there may be zero
279      space overhead, but it's all allocated inside the object.)
280    </para>
281    <para>
282      <emphasis>A container&lt;bool&gt;.&nbsp;&nbsp;</emphasis> The
283      Committee made provision for the space savings possible with that
284      (N/8) usage previously mentioned, so that you don't have to do
285      wasteful things like <code>Container&lt;char&gt;</code> or
286      <code>Container&lt;short int&gt;</code>.  Specifically,
287      <code>vector&lt;bool&gt;</code> is required to be specialized for
288      that space savings.
289    </para>
290    <para>
291      The problem is that <code>vector&lt;bool&gt;</code> doesn't
292      behave like a normal vector anymore.  There have been recent
293      journal articles which discuss the problems (the ones by Herb
294      Sutter in the May and July/August 1999 issues of C++ Report cover
295      it well).  Future revisions of the ISO C++ Standard will change
296      the requirement for <code>vector&lt;bool&gt;</code>
297      specialization.  In the meantime, <code>deque&lt;bool&gt;</code>
298      is recommended (although its behavior is sane, you probably will
299      not get the space savings, but the allocation scheme is different
300      than that of vector).
301    </para>
302    <para>
303      <emphasis>Extremely weird solutions.&nbsp;&nbsp;</emphasis> If
304      you have access to the compiler and linker at runtime, you can do
305      something insane, like figuring out just how many bits you need,
306      then writing a temporary source code file.  That file contains an
307      instantiation of <code>bitset</code> for the required number of
308      bits, inside some wrapper functions with unchanging signatures.
309      Have your program then call the compiler on that file using
310      Position Independent Code, then open the newly-created object
311      file and load those wrapper functions.  You'll have an
312      instantiation of <code>bitset&lt;N&gt;</code> for the exact
313      <code>N</code> that you need at the time.  Don't forget to delete
314      the temporary files.  (Yes, this <emphasis>can</emphasis> be, and
315      <emphasis>has been</emphasis>, done.)
316    </para>
317    <!-- I wonder if this next paragraph will get me in trouble... -->
318    <para>
319      This would be the approach of either a visionary genius or a
320      raving lunatic, depending on your programming and management
321      style.  Probably the latter.
322    </para>
323    <para>
324      Which of the above techniques you use, if any, are up to you and
325      your intended application.  Some time/space profiling is
326      indicated if it really matters (don't just guess).  And, if you
327      manage to do anything along the lines of the third category, the
328      author would love to hear from you...
329    </para>
330    <para>
331      Also note that the implementation of bitset used in libstdc++ has
332      <ulink url="../ext/sgiexts.html#ch23">some extensions</ulink>.
333    </para>
334
335     </sect2>
336     <sect2 id="associative.bitset.type_string" xreflabel="Type String">
337       <title>Type String</title>
338       <para>
339       </para>
340    <para>
341      Bitmasks do not take char* nor const char* arguments in their
342      constructors.  This is something of an accident, but you can read
343      about the problem: follow the library's <quote>Links</quote> from
344      the homepage, and from the C++ information <quote>defect
345      reflector</quote> link, select the library issues list.  Issue
346      number 116 describes the problem.
347    </para>
348    <para>
349      For now you can simply make a temporary string object using the
350      constructor expression:
351    </para>
352    <programlisting>
353       std::bitset&lt;5&gt; b ( std::string(<quote>10110</quote>) );
354    </programlisting>
355    
356    <para>
357      instead of
358    </para>
359
360     <programlisting>
361       std::bitset&lt;5&gt; b ( <quote>10110</quote> );    // invalid
362     </programlisting>
363     </sect2>  
364   </sect1>
365
366 </chapter>
367
368 <!-- Chapter 03 : Interacting with C -->
369 <chapter id="manual.containers.c" xreflabel="Interacting with C">
370 <?dbhtml filename="containers_and_c.html"?>
371   <title>Interacting with C</title>
372
373   <sect1 id="containers.c.vs_array" xreflabel="Containers vs. Arrays">
374     <title>Containers vs. Arrays</title>
375    <para>
376      You're writing some code and can't decide whether to use builtin
377      arrays or some kind of container.  There are compelling reasons
378      to use one of the container classes, but you're afraid that
379      you'll eventually run into difficulties, change everything back
380      to arrays, and then have to change all the code that uses those
381      data types to keep up with the change.
382    </para>
383    <para>
384      If your code makes use of the standard algorithms, this isn't as
385      scary as it sounds.  The algorithms don't know, nor care, about
386      the kind of <quote>container</quote> on which they work, since
387      the algorithms are only given endpoints to work with.  For the
388      container classes, these are iterators (usually
389      <code>begin()</code> and <code>end()</code>, but not always).
390      For builtin arrays, these are the address of the first element
391      and the <ulink
392      url="../24_iterators/howto.html#2">past-the-end</ulink> element.
393    </para>
394    <para>
395      Some very simple wrapper functions can hide all of that from the
396      rest of the code.  For example, a pair of functions called
397      <code>beginof</code> can be written, one that takes an array,
398      another that takes a vector.  The first returns a pointer to the
399      first element, and the second returns the vector's
400      <code>begin()</code> iterator.
401    </para>
402    <para>
403      The functions should be made template functions, and should also
404      be declared inline.  As pointed out in the comments in the code
405      below, this can lead to <code>beginof</code> being optimized out
406      of existence, so you pay absolutely nothing in terms of increased
407      code size or execution time.
408    </para>
409    <para>
410      The result is that if all your algorithm calls look like
411    </para>
412    <programlisting>
413    std::transform(beginof(foo), endof(foo), beginof(foo), SomeFunction);
414    </programlisting>
415    <para>
416      then the type of foo can change from an array of ints to a vector
417      of ints to a deque of ints and back again, without ever changing
418      any client code.
419    </para>
420    <para>
421      This author has a collection of such functions, called
422      <quote>*of</quote> because they all extend the builtin
423      <quote>sizeof</quote>.  It started with some Usenet discussions
424      on a transparent way to find the length of an array.  A
425      simplified and much-reduced version for easier reading is <ulink
426      url="wrappers_h.txt">given here</ulink>.
427    </para>
428    <para>
429      Astute readers will notice two things at once: first, that the
430      container class is still a <code>vector&lt;T&gt;</code> instead
431      of a more general <code>Container&lt;T&gt;</code>.  This would
432      mean that three functions for <code>deque</code> would have to be
433      added, another three for <code>list</code>, and so on.  This is
434      due to problems with getting template resolution correct; I find
435      it easier just to give the extra three lines and avoid confusion.
436    </para>
437    <para>
438      Second, the line
439    </para>
440    <programlisting>
441     inline unsigned int lengthof (T (&amp;)[sz]) { return sz; } 
442    </programlisting>
443    <para>
444      looks just weird!  Hint:  unused parameters can be left nameless.
445    </para>
446   </sect1>
447   
448 </chapter>
449
450 </part>