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