3 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
4 <meta name="AUTHOR" content="pme@gcc.gnu.org (Phil Edwards)" />
5 <meta name="KEYWORDS" content="HOWTO, libstdc++, GCC, g++, libg++, STL" />
6 <meta name="DESCRIPTION" content="HOWTO for the libstdc++ chapter 23." />
7 <meta name="GENERATOR" content="vi and eight fingers" />
8 <title>libstdc++-v3 HOWTO: Chapter 23</title>
9 <link rel="StyleSheet" href="../lib3styles.css" />
13 <h1 class="centered"><a name="top">Chapter 23: Containers</a></h1>
15 <p>Chapter 23 deals with container classes and what they offer.
19 <!-- ####################################################### -->
23 <li><a href="#1">Making code unaware of the container/array difference</a></li>
24 <li><a href="#2">Variable-sized bitmasks</a></li>
25 <li><a href="#3">Containers and multithreading</a></li>
26 <li><a href="#4">"Hinting" during insertion</a></li>
27 <li><a href="#5">Bitmasks and string arguments</a></li>
28 <li><a href="#6"><code>std::list::size()</code> is O(n)!</a></li>
29 <li><a href="#7">Space overhead management for vectors</a></li>
34 <!-- ####################################################### -->
36 <h2><a name="1">Making code unaware of the container/array difference</a></h2>
37 <p>You're writing some code and can't decide whether to use builtin
38 arrays or some kind of container. There are compelling reasons
39 to use one of the container classes, but you're afraid that you'll
40 eventually run into difficulties, change everything back to arrays,
41 and then have to change all the code that uses those data types to
42 keep up with the change.
44 <p>If your code makes use of the standard algorithms, this isn't as
45 scary as it sounds. The algorithms don't know, nor care, about
46 the kind of "container" on which they work, since the
47 algorithms are only given endpoints to work with. For the container
48 classes, these are iterators (usually <code>begin()</code> and
49 <code>end()</code>, but not always). For builtin arrays, these are
50 the address of the first element and the
51 <a href="../24_iterators/howto.html#2">past-the-end</a> element.
53 <p>Some very simple wrapper functions can hide all of that from the
54 rest of the code. For example, a pair of functions called
55 <code>beginof</code> can be written, one that takes an array, another
56 that takes a vector. The first returns a pointer to the first
57 element, and the second returns the vector's <code>begin()</code>
60 <p>The functions should be made template functions, and should also
61 be declared inline. As pointed out in the comments in the code
62 below, this can lead to <code>beginof</code> being optimized out of
63 existence, so you pay absolutely nothing in terms of increased
64 code size or execution time.
66 <p>The result is that if all your algorithm calls look like
69 std::transform(beginof(foo), endof(foo), beginof(foo), SomeFunction);</pre>
70 <p>then the type of foo can change from an array of ints to a vector
71 of ints to a deque of ints and back again, without ever changing any
74 <p>This author has a collection of such functions, called "*of"
75 because they all extend the builtin "sizeof". It started
76 with some Usenet discussions on a transparent way to find the length
77 of an array. A simplified and much-reduced version for easier
78 reading is <a href="wrappers_h.txt">given here</a>.
80 <p>Astute readers will notice two things at once: first, that the
81 container class is still a <code>vector<T></code> instead of a
82 more general <code>Container<T></code>. This would mean that
83 three functions for <code>deque</code> would have to be added, another
84 three for <code>list</code>, and so on. This is due to problems with
85 getting template resolution correct; I find it easier just to
86 give the extra three lines and avoid confusion.
91 inline unsigned int lengthof (T (&)[sz]) { return sz; } </pre>
92 <p>looks just weird! Hint: unused parameters can be left nameless.
94 <p>Return <a href="#top">to top of page</a> or
95 <a href="../faq/index.html">to the FAQ</a>.
99 <h2><a name="2">Variable-sized bitmasks</a></h2>
100 <p>No, you cannot write code of the form
102 <!-- Careful, the leading spaces in PRE show up directly. -->
104 #include <bitset>
108 std::bitset<n> bits;
111 <p>because <code>n</code> must be known at compile time. Your compiler is
112 correct; it is not a bug. That's the way templates work. (Yes, it
113 <em>is</em> a feature.)
115 <p>There are a couple of ways to handle this kind of thing. Please
116 consider all of them before passing judgement. They include, in
120 <li>A very large N in <code>bitset<N></code>.</li>
121 <li>A container<bool>.</li>
122 <li>Extremely weird solutions.</li>
124 <p><strong>A very large N in
125 <code>bitset<N></code>. </strong> It has
126 been pointed out a few times in newsgroups that N bits only takes up
127 (N/8) bytes on most systems, and division by a factor of eight is pretty
128 impressive when speaking of memory. Half a megabyte given over to a
129 bitset (recall that there is zero space overhead for housekeeping info;
130 it is known at compile time exactly how large the set is) will hold over
131 four million bits. If you're using those bits as status flags (e.g.,
132 "changed"/"unchanged" flags), that's a <em>lot</em>
135 <p>You can then keep track of the "maximum bit used" during some
136 testing runs on representative data, make note of how many of those bits
137 really need to be there, and then reduce N to a smaller number. Leave
138 some extra space, of course. (If you plan to write code like the
139 incorrect example above, where the bitset is a local variable, then you
140 may have to talk your compiler into allowing that much stack space;
141 there may be zero space overhead, but it's all allocated inside the
144 <p><strong>A container<bool>. </strong> The Committee
146 for the space savings possible with that (N/8) usage previously mentioned,
147 so that you don't have to do wasteful things like
148 <code>Container<char></code> or
149 <code>Container<short int></code>.
150 Specifically, <code>vector<bool></code> is required to be
151 specialized for that space savings.
153 <p>The problem is that <code>vector<bool></code> doesn't behave like a
154 normal vector anymore. There have been recent journal articles which
155 discuss the problems (the ones by Herb Sutter in the May and
156 July/August 1999 issues of
157 <u>C++ Report</u> cover it well). Future revisions of the ISO C++
158 Standard will change the requirement for <code>vector<bool></code>
159 specialization. In the meantime, <code>deque<bool></code> is
160 recommended (although its behavior is sane, you probably will not get
161 the space savings, but the allocation scheme is different than that
164 <p><strong>Extremely weird solutions. </strong> If you have
166 the compiler and linker at runtime, you can do something insane, like
167 figuring out just how many bits you need, then writing a temporary
168 source code file. That file contains an instantiation of
170 for the required number of bits, inside some wrapper functions with
171 unchanging signatures. Have your program then call the
172 compiler on that file using Position Independent Code, then open the
173 newly-created object file and load those wrapper functions. You'll have
174 an instantiation of <code>bitset<N></code> for the exact
176 that you need at the time. Don't forget to delete the temporary files.
177 (Yes, this <em>can</em> be, and <em>has been</em>, done.)
179 <!-- I wonder if this next paragraph will get me in trouble... -->
180 <p>This would be the approach of either a visionary genius or a raving
181 lunatic, depending on your programming and management style. Probably
184 <p>Which of the above techniques you use, if any, are up to you and your
185 intended application. Some time/space profiling is indicated if it
186 really matters (don't just guess). And, if you manage to do anything
187 along the lines of the third category, the author would love to hear
190 <p>Also note that the implementation of bitset used in libstdc++-v3 has
191 <a href="../ext/sgiexts.html#ch23">some extensions</a>.
193 <p>Return <a href="#top">to top of page</a> or
194 <a href="../faq/index.html">to the FAQ</a>.
198 <h2><a name="3">Containers and multithreading</a></h2>
199 <p>This section discusses issues surrounding the design of
200 multithreaded applications which use Standard C++ containers.
201 All information in this section is current as of the gcc 3.0
202 release and all later point releases. Although earlier gcc
203 releases had a different approach to threading configuration and
204 proper compilation, the basic code design rules presented here
205 were similar. For information on all other aspects of
206 multithreading as it relates to libstdc++, including details on
207 the proper compilation of threaded code (and compatibility between
208 threaded and non-threaded code), see Chapter 17.
210 <p>Two excellent pages to read when working with the Standard C++
211 containers and threads are
212 <a href="http://www.sgi.com/tech/stl/thread_safety.html">SGI's
213 http://www.sgi.com/tech/stl/thread_safety.html</a> and
214 <a href="http://www.sgi.com/tech/stl/Allocators.html">SGI's
215 http://www.sgi.com/tech/stl/Allocators.html</a>.
217 <p><em>However, please ignore all discussions about the user-level
218 configuration of the lock implementation inside the STL
219 container-memory allocator on those pages. For the sake of this
220 discussion, libstdc++-v3 configures the SGI STL implementation,
221 not you. This is quite different from how gcc pre-3.0 worked.
222 In particular, past advice was for people using g++ to
223 explicitly define _PTHREADS or other macros or port-specific
224 compilation options on the command line to get a thread-safe
225 STL. This is no longer required for any port and should no
226 longer be done unless you really know what you are doing and
227 assume all responsibility.</em>
229 <p>Since the container implementation of libstdc++-v3 uses the SGI
230 code, we use the same definition of thread safety as SGI when
231 discussing design. A key point that beginners may miss is the
232 fourth major paragraph of the first page mentioned above
233 ("For most clients,"...), which points out that
234 locking must nearly always be done outside the container, by
235 client code (that'd be you, not us). There is a notable
236 exceptions to this rule. Allocators called while a container or
237 element is constructed uses an internal lock obtained and
238 released solely within libstdc++-v3 code (in fact, this is the
239 reason STL requires any knowledge of the thread configuration).
241 <p>For implementing a container which does its own locking, it is
242 trivial to provide a wrapper class which obtains the lock (as
243 SGI suggests), performs the container operation, and then
244 releases the lock. This could be templatized <em>to a certain
245 extent</em>, on the underlying container and/or a locking
246 mechanism. Trying to provide a catch-all general template
247 solution would probably be more trouble than it's worth.
249 <p>The STL implementation is currently configured to use the
250 high-speed caching memory allocator. If you absolutely think
251 you must change this on a global basis for your platform to better
252 support multi-threading, then please consult all commentary in
253 include/bits/stl_alloc.h and the allocators link below.
256 <p>(Explicit warning since so many people get confused while
259 <p><strong>Adding -D__USE_MALLOC on the command
260 line is almost certainly a bad idea.</strong> Memory efficiency is
261 almost guaranteed to suffer as a result; this is
262 <a href="http://gcc.gnu.org/ml/libstdc++/2001-05/msg00136.html">why
263 we disabled it for 3.0 in the first place</a>.
265 <p>Related to threading or otherwise, the current recommendation is
266 that users not add any macro defines on the command line to remove or
267 otherwise disable features of libstdc++-v3. There is
268 no condition under which it will help you without causing other
269 issues to perhaps raise up (possible linkage/ABI problems). In
270 particular, __USE_MALLOC should only be added to a libstdc++-v3
271 configuration file, include/bits/c++config (where such user
272 action is cautioned against), and the entire library should be
273 rebuilt. If you do not, then you might be violating the
274 one-definition rule of C/C++ and you might cause yourself untold
278 <p>If you find any platform where gcc reports a
279 threading model other than single, and where libstdc++-v3 builds
280 a buggy container allocator when used with threads unless you
281 define __USE_MALLOC, we want to hear about it ASAP. In the
282 past, correctness was the main reason people were led to believe
283 that they should define __USE_MALLOC when using threads.
285 <p>There is a better way (not standardized yet): It is possible to
286 force the malloc-based allocator on a per-case-basis for some
287 application code. The library team generally believes that this
288 is a better way to tune an application for high-speed using this
289 implementation of the STL. There is
290 <a href="../ext/howto.html#3">more information on allocators here</a>.
292 <p>Return <a href="#top">to top of page</a> or
293 <a href="../faq/index.html">to the FAQ</a>.
297 <h2><a name="4">"Hinting" during insertion</a></h2>
298 <p>Section [23.1.2], Table 69, of the C++ standard lists this function
299 for all of the associative containers (map, set, etc):
303 <p>where 'p' is an iterator into the container 'a', and 't' is the item
304 to insert. The standard says that "iterator p is a hint
305 pointing to where the insert should start to search," but
306 specifies nothing more. (LWG Issue #233, currently in review,
307 addresses this topic, but I will ignore it here because it is not yet
310 <p>Here we'll describe how the hinting works in the libstdc++-v3
311 implementation, and what you need to do in order to take advantage of
312 it. (Insertions can change from logarithmic complexity to amortized
313 constant time, if the hint is properly used.) Also, since the current
314 implementation is based on the SGI STL one, these points may hold true
315 for other library implementations also, since the HP/SGI code is used
318 <p>In the following text, the phrases <em>greater than</em> and <em>less
319 than</em> refer to the results of the strict weak ordering imposed on
320 the container by its comparison object, which defaults to (basically)
321 "<". Using those phrases is semantically sloppy, but I
322 didn't want to get bogged down in syntax. I assume that if you are
323 intelligent enough to use your own comparison objects, you are also
324 intelligent enough to assign "greater" and "lesser"
325 their new meanings in the next paragraph. *grin*
327 <p>If the <code>hint</code> parameter ('p' above) is equivalent to:
330 <li><code>begin()</code>, then the item being inserted should have a key
331 less than all the other keys in the container. The item will
332 be inserted at the beginning of the container, becoming the new
333 entry at <code>begin()</code>.
335 <li><code>end()</code>, then the item being inserted should have a key
336 greater than all the other keys in the container. The item will
337 be inserted at the end of the container, becoming the new entry
338 at <code>end()</code>.
340 <li>neither <code>begin()</code> nor <code>end()</code>, then: Let <code>h</code>
341 be the entry in the container pointed to by <code>hint</code>, that
342 is, <code>h = *hint</code>. Then the item being inserted should have
343 a key less than that of <code>h</code>, and greater than that of the
344 item preceding <code>h</code>. The new item will be inserted
345 between <code>h</code> and <code>h</code>'s predecessor.
348 <p>For <code>multimap</code> and <code>multiset</code>, the restrictions are
349 slightly looser: "greater than" should be replaced by
350 "not less than" and "less than" should be replaced
351 by "not greater than." (Why not replace greater with
352 greater-than-or-equal-to? You probably could in your head, but the
353 mathematicians will tell you that it isn't the same thing.)
355 <p>If the conditions are not met, then the hint is not used, and the
356 insertion proceeds as if you had called <code> a.insert(t) </code>
357 instead. (<strong>Note </strong> that GCC releases prior to 3.0.2
358 had a bug in the case with <code>hint == begin()</code> for the
359 <code>map</code> and <code>set</code> classes. You should not use a hint
360 argument in those releases.)
362 <p>This behavior goes well with other container's <code>insert()</code>
363 functions which take an iterator: if used, the new item will be
364 inserted before the iterator passed as an argument, same as the other
365 containers. The exception
366 (in a sense) is with a hint of <code>end()</code>: the new item will
367 actually be inserted after <code>end()</code>, but it also becomes the
368 new <code>end()</code>.
370 <p><strong>Note </strong> also that the hint in this implementation is a
371 one-shot. The insertion-with-hint routines check the immediately
372 surrounding entries to ensure that the new item would in fact belong
373 there. If the hint does not point to the correct place, then no
374 further local searching is done; the search begins from scratch in
375 logarithmic time. (Further local searching would only increase the
376 time required when the hint is too far off.)
378 <p>Return <a href="#top">to top of page</a> or
379 <a href="../faq/index.html">to the FAQ</a>.
383 <h2><a name="5">Bitmasks and string arguments</a></h2>
384 <p>Bitmasks do not take char* nor const char* arguments in their
385 constructors. This is something of an accident, but you can read
386 about the problem: follow the library's "Links" from the
387 homepage, and from the C++ information "defect reflector"
388 link, select the library issues list. Issue number 116 describes the
391 <p>For now you can simply make a temporary string object using the
392 constructor expression:
395 std::bitset<5> b ( std::string("10110") );
399 std::bitset<5> b ( "10110" ); // invalid
401 <p>Return <a href="#top">to top of page</a> or
402 <a href="../faq/index.html">to the FAQ</a>.
406 <h2><a name="6"><code>std::list::size()</code> is O(n)!</a></h2>
407 <p>Yes it is, and that's okay. This is a decision that we preserved when
408 we imported SGI's STL implementation. The following is quoted from
409 <a href="http://www.sgi.com/tech/stl/FAQ.html">their FAQ</a>:
412 <p>The size() member function, for list and slist, takes time
413 proportional to the number of elements in the list. This was a
414 deliberate tradeoff. The only way to get a constant-time size() for
415 linked lists would be to maintain an extra member variable containing
416 the list's size. This would require taking extra time to update that
417 variable (it would make splice() a linear time operation, for example),
418 and it would also make the list larger. Many list algorithms don't
419 require that extra word (algorithms that do require it might do better
420 with vectors than with lists), and, when it is necessary to maintain
421 an explicit size count, it's something that users can do themselves.
423 <p>This choice is permitted by the C++ standard. The standard says that
424 size() "should" be constant time, and "should"
425 does not mean the same thing as "shall". This is the
426 officially recommended ISO wording for saying that an implementation
427 is supposed to do something unless there is a good reason not to.
429 <p>One implication of linear time size(): you should never write
434 Instead, you should write
439 <p>Return <a href="#top">to top of page</a> or
440 <a href="../faq/index.html">to the FAQ</a>.
444 <h2><a name="7">Space overhead management for vectors</a></h2>
446 <a href="http://gcc.gnu.org/ml/libstdc++/2002-04/msg00105.html">this
447 message to the list</a>, Daniel Kostecky announced work on an
448 alternate form of <code>std::vector</code> that would support hints
449 on the number of elements to be over-allocated. The design was also
450 described, along with possible implementation choices.
452 <p>The first two alpha releases were announced
453 <a href="http://gcc.gnu.org/ml/libstdc++/2002-07/msg00048.html">here</a>
455 <a href="http://gcc.gnu.org/ml/libstdc++/2002-07/msg00111.html">here</a>.
456 The releases themselves are available at
457 <a href="http://www.kotelna.sk/dk/sw/caphint/">
458 http://www.kotelna.sk/dk/sw/caphint/</a>.
460 <p>Return <a href="#top">to top of page</a> or
461 <a href="../faq/index.html">to the FAQ</a>.
465 <!-- ####################################################### -->
468 <p class="fineprint"><em>
469 See <a href="../17_intro/license.html">license.html</a> for copying conditions.
470 Comments and suggestions are welcome, and may be sent to
471 <a href="mailto:libstdc++@gcc.gnu.org">the libstdc++ mailing list</a>.