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"?>
22 <indexterm><primary>Containers</primary></indexterm>
25 <!-- Chapter 01 : Sequences -->
26 <chapter id="manual.containers.sequences" xreflabel="Sequences">
27 <?dbhtml filename="sequences.html"?>
28 <title>Sequences</title>
30 <sect1 id="containers.sequences.list" xreflabel="list">
31 <?dbhtml filename="list.html"?>
33 <sect2 id="sequences.list.size" xreflabel="list::size() is O(n)">
34 <title>list::size() is O(n)</title>
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
39 url="http://www.sgi.com/tech/stl/FAQ.html">their FAQ</ulink>:
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
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.
65 One implication of linear time size(): you should never write
73 Instead, you should write
84 <sect1 id="containers.sequences.vector" xreflabel="vector">
85 <?dbhtml filename="vector.html"?>
89 <sect2 id="sequences.vector.management" xreflabel="Space Overhead Management">
90 <title>Space Overhead Management</title>
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.
100 The first two alpha releases were announced <ulink
101 url="http://gcc.gnu.org/ml/libstdc++/2002-07/msg00048.html">here</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>.
112 <!-- Chapter 02 : Associative -->
113 <chapter id="manual.containers.associative" xreflabel="Associative">
114 <?dbhtml filename="associative.html"?>
115 <title>Associative</title>
117 <sect1 id="containers.associative.insert_hints" xreflabel="Insertion Hints">
118 <title>Insertion Hints</title>
120 Section [23.1.2], Table 69, of the C++ standard lists this
121 function for all of the associative containers (map, set, etc):
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,
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.
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
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><</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
160 If the <code>hint</code> parameter ('p' above) is equivalent to:
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>.
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>.
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.
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.)
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.)
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.
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.
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>
231 No, you cannot write code of the form
233 <!-- Careful, the leading spaces in PRE show up directly. -->
235 #include <bitset>
239 std::bitset<n> bits;
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.)
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
254 <listitem><para>A very large N in <code>bitset<N></code>.</para></listitem>
255 <listitem><para>A container<bool>.</para></listitem>
256 <listitem><para>Extremely weird solutions.</para></listitem>
259 <emphasis>A very large N in
260 <code>bitset<N></code>. </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.
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.)
282 <emphasis>A container<bool>. </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<char></code> or
286 <code>Container<short int></code>. Specifically,
287 <code>vector<bool></code> is required to be specialized for
291 The problem is that <code>vector<bool></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<bool></code>
297 specialization. In the meantime, <code>deque<bool></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).
303 <emphasis>Extremely weird solutions. </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<N></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.)
317 <!-- I wonder if this next paragraph will get me in trouble... -->
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.
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...
331 Also note that the implementation of bitset used in libstdc++ has
332 <ulink url="../ext/sgiexts.html#ch23">some extensions</ulink>.
336 <sect2 id="associative.bitset.type_string" xreflabel="Type String">
337 <title>Type String</title>
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.
349 For now you can simply make a temporary string object using the
350 constructor expression:
353 std::bitset<5> b ( std::string(<quote>10110</quote>) );
361 std::bitset<5> b ( <quote>10110</quote> ); // invalid
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>
373 <sect1 id="containers.c.vs_array" xreflabel="Containers vs. Arrays">
374 <title>Containers vs. Arrays</title>
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.
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
392 url="../24_iterators/howto.html#2">past-the-end</ulink> element.
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.
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.
410 The result is that if all your algorithm calls look like
413 std::transform(beginof(foo), endof(foo), beginof(foo), SomeFunction);
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
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>.
429 Astute readers will notice two things at once: first, that the
430 container class is still a <code>vector<T></code> instead
431 of a more general <code>Container<T></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.
441 inline unsigned int lengthof (T (&)[sz]) { return sz; }
444 looks just weird! Hint: unused parameters can be left nameless.