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>.
109 <!-- Chapter 02 : Associative -->
110 <chapter id="manual.containers.associative" xreflabel="Associative">
111 <?dbhtml filename="associative.html"?>
112 <title>Associative</title>
114 <sect1 id="containers.associative.insert_hints" xreflabel="Insertion Hints">
115 <title>Insertion Hints</title>
117 Section [23.1.2], Table 69, of the C++ standard lists this
118 function for all of the associative containers (map, set, etc):
124 where 'p' is an iterator into the container 'a', and 't' is the
125 item to insert. The standard says that <quote><code>t</code> is
126 inserted as close as possible to the position just prior to
127 <code>p</code>.</quote> (Library DR #233 addresses this topic,
129 url="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1780.html">N1780</ulink>.
130 Since version 4.2 GCC implements the resolution to DR 233, so
131 that insertions happen as close as possible to the hint. For
132 earlier releases the hint was only used as described below.
135 Here we'll describe how the hinting works in the libstdc++
136 implementation, and what you need to do in order to take
137 advantage of it. (Insertions can change from logarithmic
138 complexity to amortized constant time, if the hint is properly
139 used.) Also, since the current implementation is based on the
140 SGI STL one, these points may hold true for other library
141 implementations also, since the HP/SGI code is used in a lot of
145 In the following text, the phrases <emphasis>greater
146 than</emphasis> and <emphasis>less than</emphasis> refer to the
147 results of the strict weak ordering imposed on the container by
148 its comparison object, which defaults to (basically)
149 <quote><</quote>. Using those phrases is semantically sloppy,
150 but I didn't want to get bogged down in syntax. I assume that if
151 you are intelligent enough to use your own comparison objects,
152 you are also intelligent enough to assign <quote>greater</quote>
153 and <quote>lesser</quote> their new meanings in the next
157 If the <code>hint</code> parameter ('p' above) is equivalent to:
162 <code>begin()</code>, then the item being inserted should
163 have a key less than all the other keys in the container.
164 The item will be inserted at the beginning of the container,
165 becoming the new entry at <code>begin()</code>.
170 <code>end()</code>, then the item being inserted should have
171 a key greater than all the other keys in the container. The
172 item will be inserted at the end of the container, becoming
173 the new entry before <code>end()</code>.
178 neither <code>begin()</code> nor <code>end()</code>, then:
179 Let <code>h</code> be the entry in the container pointed to
180 by <code>hint</code>, that is, <code>h = *hint</code>. Then
181 the item being inserted should have a key less than that of
182 <code>h</code>, and greater than that of the item preceding
183 <code>h</code>. The new item will be inserted between
184 <code>h</code> and <code>h</code>'s predecessor.
189 For <code>multimap</code> and <code>multiset</code>, the
190 restrictions are slightly looser: <quote>greater than</quote>
191 should be replaced by <quote>not less than</quote>and <quote>less
192 than</quote> should be replaced by <quote>not greater
193 than.</quote> (Why not replace greater with
194 greater-than-or-equal-to? You probably could in your head, but
195 the mathematicians will tell you that it isn't the same thing.)
198 If the conditions are not met, then the hint is not used, and the
199 insertion proceeds as if you had called <code> a.insert(t)
200 </code> instead. (<emphasis>Note </emphasis> that GCC releases
201 prior to 3.0.2 had a bug in the case with <code>hint ==
202 begin()</code> for the <code>map</code> and <code>set</code>
203 classes. You should not use a hint argument in those releases.)
206 This behavior goes well with other containers'
207 <code>insert()</code> functions which take an iterator: if used,
208 the new item will be inserted before the iterator passed as an
209 argument, same as the other containers.
212 <emphasis>Note </emphasis> also that the hint in this
213 implementation is a one-shot. The older insertion-with-hint
214 routines check the immediately surrounding entries to ensure that
215 the new item would in fact belong there. If the hint does not
216 point to the correct place, then no further local searching is
217 done; the search begins from scratch in logarithmic time.
222 <sect1 id="containers.associative.bitset" xreflabel="bitset">
223 <?dbhtml filename="bitset.html"?>
224 <title>bitset</title>
225 <sect2 id="associative.bitset.size_variable" xreflabel="Variable">
226 <title>Size Variable</title>
228 No, you cannot write code of the form
230 <!-- Careful, the leading spaces in PRE show up directly. -->
232 #include <bitset>
236 std::bitset<n> bits;
241 because <code>n</code> must be known at compile time. Your
242 compiler is correct; it is not a bug. That's the way templates
243 work. (Yes, it <emphasis>is</emphasis> a feature.)
246 There are a couple of ways to handle this kind of thing. Please
247 consider all of them before passing judgement. They include, in
251 <listitem><para>A very large N in <code>bitset<N></code>.</para></listitem>
252 <listitem><para>A container<bool>.</para></listitem>
253 <listitem><para>Extremely weird solutions.</para></listitem>
256 <emphasis>A very large N in
257 <code>bitset<N></code>. </emphasis> It has been
258 pointed out a few times in newsgroups that N bits only takes up
259 (N/8) bytes on most systems, and division by a factor of eight is
260 pretty impressive when speaking of memory. Half a megabyte given
261 over to a bitset (recall that there is zero space overhead for
262 housekeeping info; it is known at compile time exactly how large
263 the set is) will hold over four million bits. If you're using
264 those bits as status flags (e.g.,
265 <quote>changed</quote>/<quote>unchanged</quote> flags), that's a
266 <emphasis>lot</emphasis> of state.
269 You can then keep track of the <quote>maximum bit used</quote>
270 during some testing runs on representative data, make note of how
271 many of those bits really need to be there, and then reduce N to
272 a smaller number. Leave some extra space, of course. (If you
273 plan to write code like the incorrect example above, where the
274 bitset is a local variable, then you may have to talk your
275 compiler into allowing that much stack space; there may be zero
276 space overhead, but it's all allocated inside the object.)
279 <emphasis>A container<bool>. </emphasis> The
280 Committee made provision for the space savings possible with that
281 (N/8) usage previously mentioned, so that you don't have to do
282 wasteful things like <code>Container<char></code> or
283 <code>Container<short int></code>. Specifically,
284 <code>vector<bool></code> is required to be specialized for
288 The problem is that <code>vector<bool></code> doesn't
289 behave like a normal vector anymore. There have been
290 journal articles which discuss the problems (the ones by Herb
291 Sutter in the May and July/August 1999 issues of C++ Report cover
292 it well). Future revisions of the ISO C++ Standard will change
293 the requirement for <code>vector<bool></code>
294 specialization. In the meantime, <code>deque<bool></code>
295 is recommended (although its behavior is sane, you probably will
296 not get the space savings, but the allocation scheme is different
297 than that of vector).
300 <emphasis>Extremely weird solutions. </emphasis> If
301 you have access to the compiler and linker at runtime, you can do
302 something insane, like figuring out just how many bits you need,
303 then writing a temporary source code file. That file contains an
304 instantiation of <code>bitset</code> for the required number of
305 bits, inside some wrapper functions with unchanging signatures.
306 Have your program then call the compiler on that file using
307 Position Independent Code, then open the newly-created object
308 file and load those wrapper functions. You'll have an
309 instantiation of <code>bitset<N></code> for the exact
310 <code>N</code> that you need at the time. Don't forget to delete
311 the temporary files. (Yes, this <emphasis>can</emphasis> be, and
312 <emphasis>has been</emphasis>, done.)
314 <!-- I wonder if this next paragraph will get me in trouble... -->
316 This would be the approach of either a visionary genius or a
317 raving lunatic, depending on your programming and management
318 style. Probably the latter.
321 Which of the above techniques you use, if any, are up to you and
322 your intended application. Some time/space profiling is
323 indicated if it really matters (don't just guess). And, if you
324 manage to do anything along the lines of the third category, the
325 author would love to hear from you...
328 Also note that the implementation of bitset used in libstdc++ has
329 <link linkend="manual.ext.containers.sgi">some extensions</link>.
333 <sect2 id="associative.bitset.type_string" xreflabel="Type String">
334 <title>Type String</title>
338 Bitmasks do not take char* nor const char* arguments in their
339 constructors. This is something of an accident, but you can read
340 about the problem: follow the library's <quote>Links</quote> from
341 the homepage, and from the C++ information <quote>defect
342 reflector</quote> link, select the library issues list. Issue
343 number 116 describes the problem.
346 For now you can simply make a temporary string object using the
347 constructor expression:
350 std::bitset<5> b ( std::string(<quote>10110</quote>) );
358 std::bitset<5> b ( <quote>10110</quote> ); // invalid
365 <!-- Chapter 03 : Interacting with C -->
366 <chapter id="manual.containers.c" xreflabel="Interacting with C">
367 <?dbhtml filename="containers_and_c.html"?>
368 <title>Interacting with C</title>
370 <sect1 id="containers.c.vs_array" xreflabel="Containers vs. Arrays">
371 <title>Containers vs. Arrays</title>
373 You're writing some code and can't decide whether to use builtin
374 arrays or some kind of container. There are compelling reasons
375 to use one of the container classes, but you're afraid that
376 you'll eventually run into difficulties, change everything back
377 to arrays, and then have to change all the code that uses those
378 data types to keep up with the change.
381 If your code makes use of the standard algorithms, this isn't as
382 scary as it sounds. The algorithms don't know, nor care, about
383 the kind of <quote>container</quote> on which they work, since
384 the algorithms are only given endpoints to work with. For the
385 container classes, these are iterators (usually
386 <code>begin()</code> and <code>end()</code>, but not always).
387 For builtin arrays, these are the address of the first element
388 and the <link linkend="iterators.predefined.end">past-the-end</link> element.
391 Some very simple wrapper functions can hide all of that from the
392 rest of the code. For example, a pair of functions called
393 <code>beginof</code> can be written, one that takes an array,
394 another that takes a vector. The first returns a pointer to the
395 first element, and the second returns the vector's
396 <code>begin()</code> iterator.
399 The functions should be made template functions, and should also
400 be declared inline. As pointed out in the comments in the code
401 below, this can lead to <code>beginof</code> being optimized out
402 of existence, so you pay absolutely nothing in terms of increased
403 code size or execution time.
406 The result is that if all your algorithm calls look like
409 std::transform(beginof(foo), endof(foo), beginof(foo), SomeFunction);
412 then the type of foo can change from an array of ints to a vector
413 of ints to a deque of ints and back again, without ever changing
419 template<typename T>
420 inline typename vector<T>::iterator
421 beginof(vector<T> &v)
422 { return v.begin(); }
424 template<typename T, unsigned int sz>
426 beginof(T (&array)[sz]) { return array; }
429 template<typename T>
430 inline typename vector<T>::iterator
431 endof(vector<T> &v)
434 template<typename T, unsigned int sz>
436 endof(T (&array)[sz]) { return array + sz; }
439 template<typename T>
440 inline typename vector<T>::size_type
441 lengthof(vector<T> &v)
444 template<typename T, unsigned int sz>
446 lengthof(T (&)[sz]) { return sz; }
450 Astute readers will notice two things at once: first, that the
451 container class is still a <code>vector<T></code> instead
452 of a more general <code>Container<T></code>. This would
453 mean that three functions for <code>deque</code> would have to be
454 added, another three for <code>list</code>, and so on. This is
455 due to problems with getting template resolution correct; I find
456 it easier just to give the extra three lines and avoid confusion.
462 inline unsigned int lengthof (T (&)[sz]) { return sz; }
465 looks just weird! Hint: unused parameters can be left nameless.