2 <!DOCTYPE part PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
3 "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd"
6 <part id="manual.containers" xreflabel="Containers">
7 <?dbhtml filename="containers.html"?>
20 <title>Containers</title>
22 <!-- Chapter 01 : Sequences -->
23 <chapter id="manual.containers.sequences" xreflabel="Sequences">
24 <title>Sequences</title>
26 <sect1 id="containers.sequences.list" xreflabel="list">
28 <sect2 id="sequences.list.size" xreflabel="list::size() is O(n)">
29 <title>list::size() is O(n)</title>
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
34 url="http://www.sgi.com/tech/stl/FAQ.html">their FAQ</ulink>:
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
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.
60 One implication of linear time size(): you should never write
68 Instead, you should write
79 <sect1 id="containers.sequences.vector" xreflabel="vector">
83 <sect2 id="sequences.vector.management" xreflabel="Space Overhead Management">
84 <title>Space Overhead Management</title>
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.
94 The first two alpha releases were announced <ulink
95 url="http://gcc.gnu.org/ml/libstdc++/2002-07/msg00048.html">here</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>.
106 <!-- Chapter 02 : Associative -->
107 <chapter id="manual.containers.associative" xreflabel="Associative">
108 <title>Associative</title>
110 <sect1 id="containers.associative.insert_hints" xreflabel="Insertion Hints">
111 <title>Insertion Hints</title>
113 Section [23.1.2], Table 69, of the C++ standard lists this
114 function for all of the associative containers (map, set, etc):
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,
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.
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
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><</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
153 If the <code>hint</code> parameter ('p' above) is equivalent to:
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>.
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>.
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.
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.)
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.)
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.
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.
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>
223 No, you cannot write code of the form
225 <!-- Careful, the leading spaces in PRE show up directly. -->
227 #include <bitset>
231 std::bitset<n> bits;
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.)
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
246 <listitem><para>A very large N in <code>bitset<N></code>.</para></listitem>
247 <listitem><para>A container<bool>.</para></listitem>
248 <listitem><para>Extremely weird solutions.</para></listitem>
251 <emphasis>A very large N in
252 <code>bitset<N></code>. </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.
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.)
274 <emphasis>A container<bool>. </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<char></code> or
278 <code>Container<short int></code>. Specifically,
279 <code>vector<bool></code> is required to be specialized for
283 The problem is that <code>vector<bool></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<bool></code>
289 specialization. In the meantime, <code>deque<bool></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).
295 <emphasis>Extremely weird solutions. </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<N></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.)
309 <!-- I wonder if this next paragraph will get me in trouble... -->
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.
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...
323 Also note that the implementation of bitset used in libstdc++ has
324 <ulink url="../ext/sgiexts.html#ch23">some extensions</ulink>.
328 <sect2 id="associative.bitset.type_string" xreflabel="Type String">
329 <title>Type String</title>
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.
341 For now you can simply make a temporary string object using the
342 constructor expression:
345 std::bitset<5> b ( std::string(<quote>10110</quote>) );
353 std::bitset<5> b ( <quote>10110</quote> ); // invalid
360 <!-- Chapter 03 : Interacting with C -->
361 <chapter id="manual.containers.c" xreflabel="Interacting with C">
362 <title>Interacting with C</title>
364 <sect1 id="containers.c.vs_array" xreflabel="Containers vs. Arrays">
365 <title>Containers vs. Arrays</title>
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.
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
383 url="../24_iterators/howto.html#2">past-the-end</ulink> element.
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.
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.
401 The result is that if all your algorithm calls look like
404 std::transform(beginof(foo), endof(foo), beginof(foo), SomeFunction);
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
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>.
420 Astute readers will notice two things at once: first, that the
421 container class is still a <code>vector<T></code> instead
422 of a more general <code>Container<T></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.
432 inline unsigned int lengthof (T (&)[sz]) { return sz; }
435 looks just weird! Hint: unused parameters can be left nameless.