Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: downloads/boost_1_33_1/libs/ptr_container/doc/tutorial.html @ 12

Last change on this file since 12 was 12, checked in by landauf, 17 years ago

added boost

File size: 14.7 KB
Line 
1<?xml version="1.0" encoding="utf-8" ?>
2<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
4<head>
5<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
6<meta name="generator" content="Docutils 0.3.9: http://docutils.sourceforge.net/" />
7<title>Boost Pointer Container Library</title>
8<link rel="stylesheet" href="default.css" type="text/css" />
9</head>
10<body>
11<div class="document" id="boost-pointer-container-library">
12<h1 class="title"><img alt="Boost" src="boost.png" /> Pointer Container Library</h1>
13<h2 class="subtitle" id="tutorial">Tutorial</h2>
14<p>The tutorial shows you the most simple usage of the
15library. It is assumed that the reader is familiar
16with the use of standard containers. Although
17the tutorial is devided into sections, it is recommended
18that you read it all from top to bottom.</p>
19<ul class="simple">
20<li><a class="reference" href="#basic-usage">Basic usage</a></li>
21<li><a class="reference" href="#indirected-interface">Indirected interface</a></li>
22<li><a class="reference" href="#sequence-containers">Sequence containers</a></li>
23<li><a class="reference" href="#associative-containers">Associative containers</a></li>
24<li><a class="reference" href="#null-values">Null values</a></li>
25<li><a class="reference" href="#clonability">Clonability</a></li>
26<li><a class="reference" href="#new-functions">New functions</a></li>
27<li><a class="reference" href="#algorithms">Algorithms</a></li>
28</ul>
29<div class="section" id="basic-usage">
30<h1><a name="basic-usage">Basic usage</a></h1>
31<p>The most important aspect of a pointer container is that it manages
32memory for you. This means that you in most cases do not need to worry
33about deleting memory.</p>
34<p>Let us assume that we have an OO-hierarchy of animals</p>
35<pre class="literal-block">
36class animal : <a class="reference" href="http://www.boost.org/libs/utility/utility.htm#Class_noncopyable">boost::noncopyable</a>
37{
38public:
39    virtual      ~animal() {}
40    virtual void eat() = 0;
41    // ...
42};
43
44class mammal : public animal
45{
46    // ...
47};
48
49class bird : public animal
50{
51    // ...
52};
53</pre>
54<p>Then the managing of the animals is straight-forward. Imagine a
55Zoo:</p>
56<pre class="literal-block">
57class zoo
58{
59    boost::ptr_vector&lt;animal&gt; the_animals;
60public:
61
62    void add_animal( animal* a )
63    {
64        the_animals.push_back( a );
65    }
66};
67</pre>
68<p>Notice how just pass the class name to the container; there
69is no <tt class="docutils literal"><span class="pre">*</span></tt> to indicate it is a pointer.
70With this declaration we can now say:</p>
71<pre class="literal-block">
72zoo the_zoo;
73the_zoo.add_animal( new mammal(&quot;joe&quot;) );
74the_zoo.add_animal( new bird(&quot;dodo&quot;) );
75</pre>
76<p>Thus we heap-allocate all elements of the container
77and never rely on copy-semantics.</p>
78</div>
79<div class="section" id="indirected-interface">
80<h1><a name="indirected-interface">Indirected interface</a></h1>
81<p>As particular feature of the pointer containers is that
82the query interface is indirected. For example,</p>
83<pre class="literal-block">
84boost::ptr_vector&lt;animal&gt; vec;
85vec.push_back( new animal ); // you add it as pointer ...
86vec[0].eat();                // but get a reference back
87</pre>
88<p>This indirection also happens to iterators, so</p>
89<pre class="literal-block">
90typedef std::vector&lt;animal*&gt; std_vec;
91std_vec vec;
92...
93std_vec::iterator i = vec.begin();
94(*i)-&gt;eat(); // '*' needed
95</pre>
96<p>now becomes</p>
97<pre class="literal-block">
98typedef boost::ptr_vector&lt;animal&gt;  ptr_vec;
99ptr_vec vec;
100ptr_vec::iterator i = vec.begin();
101i-&gt;eat(); // no indirection needed
102</pre>
103</div>
104<div class="section" id="sequence-containers">
105<h1><a name="sequence-containers">Sequence containers</a></h1>
106<p>The sequence containers used when you do not need to
107keep an ordering on your elements. You can basically
108expect all operations of the normal standard containers
109to be available. So, for example, with a  <tt class="docutils literal"><span class="pre">ptr_deque</span></tt>
110and <tt class="docutils literal"><span class="pre">ptr_list</span></tt> object you can say:</p>
111<pre class="literal-block">
112boost::ptr_deque&lt;animal&gt; deq;
113deq.push_front( new animal );   
114deq.pop_front();
115</pre>
116<p>because <tt class="docutils literal"><span class="pre">std::deque</span></tt> and <tt class="docutils literal"><span class="pre">std::list</span></tt> has <tt class="docutils literal"><span class="pre">push_front()</span></tt>
117and <tt class="docutils literal"><span class="pre">pop_front</span></tt> members.</p>
118<p>If the standard sequence support
119random access, so does the pointer container; for example:</p>
120<pre class="literal-block">
121for( boost::ptr_deque&lt;animal&gt;::size_type i = 0u;
122     i != deq.size(); ++i )
123     deq[i].eat();
124</pre>
125<p>The <tt class="docutils literal"><span class="pre">ptr_vector</span></tt> also allows you to specify the size of
126the buffer to allocate; for example</p>
127<pre class="literal-block">
128boost::ptr_vector&lt;animal&gt; animals( 10u );
129</pre>
130<p>will reserve room for 10 animals.</p>
131</div>
132<div class="section" id="associative-containers">
133<h1><a name="associative-containers">Associative containers</a></h1>
134<p>To keep an ordering on our animals, we could use a <tt class="docutils literal"><span class="pre">ptr_set</span></tt>:</p>
135<pre class="literal-block">
136boost::ptr_set&lt;animal&gt; set;
137set.insert( new monkey(&quot;bobo&quot;) );
138set.insert( new whale(&quot;anna&quot;) );
139...
140</pre>
141<p>This requires that <tt class="docutils literal"><span class="pre">operator&lt;()</span></tt> is defined for animals. One
142way to do this could be</p>
143<pre class="literal-block">
144inline bool operator&lt;( const animal&amp; l, const animal&amp; r )
145{
146    return l.name() &lt; r.name();
147}
148</pre>
149<p>if we wanted to keep the animals sorted by name.</p>
150<p>Maybe you want to keep all the animals in zoo ordered wrt.
151their name, but it so happens that many animals have the
152same name. We can then use a <tt class="docutils literal"><span class="pre">ptr_multimap</span></tt>:</p>
153<pre class="literal-block">
154typedef boost::ptr_multimap&lt;std::string,animal&gt; zoo_type;
155zoo_type zoo;
156std::string bobo = &quot;bobo&quot;,
157            anna = &quot;anna&quot;;
158zoo.insert( bobo, new monkey(bobo) );
159zoo.insert( bobo, new elephant(bobo) );
160zoo.insert( anna, new whale(anna) );
161zoo.insert( anna, new emu(anna) );
162</pre>
163<p>Note that must create the key as an lvalue
164(due to exception-safety issues); the following would not
165have compiled</p>
166<pre class="literal-block">
167zoo.insert( &quot;bobo&quot;, // this is bad, but you get compile error
168            new monkey(&quot;bobo&quot;) );
169</pre>
170<p>If a multimap is not needed, we can use <tt class="docutils literal"><span class="pre">operator[]()</span></tt>
171to avoid the clumsiness:</p>
172<pre class="literal-block">
173boost::ptr_map&lt;std::string,animal&gt; animals;
174animals[&quot;bobo&quot;].set_name(&quot;bobo&quot;);
175</pre>
176<p>This requires a default constructor for animals and
177a function to do the initialization, in this case <tt class="docutils literal"><span class="pre">set_name()</span></tt>;</p>
178</div>
179<div class="section" id="null-values">
180<h1><a name="null-values">Null values</a></h1>
181<p>By default, if you try to insert null into a container, an exception
182is thrown. If you want to allow nulls, then you must
183say so explicitly when declaring the container variable</p>
184<pre class="literal-block">
185boost::ptr_vector&lt; boost::nullable&lt;animal&gt; &gt; animals_type;
186animals_type animals;
187...
188animals.insert( animals.end(), new dodo(&quot;fido&quot;) );
189animals.insert( animals.begin(), 0 ) // ok
190</pre>
191<p>Once you have inserted a null into the container, you must
192always check if the value is null before accessing the object</p>
193<pre class="literal-block">
194for( animals_type::iterator i = animals.begin();
195     i != animals.end(); ++i )
196{
197    if( !boost::is_null(i) ) // always check for validity
198        i-&gt;eat();
199}
200</pre>
201<p>If the container support random access, you may also check this as</p>
202<pre class="literal-block">
203for( animals_type::size_type i = 0u;
204     i != animals.size(); ++i )
205{
206    if( !animals.is_null(i) )
207         animals[i].eat();
208}
209</pre>
210<p>Note that it is meaningless to insert
211null into <tt class="docutils literal"><span class="pre">ptr_set</span></tt> and <tt class="docutils literal"><span class="pre">ptr_multiset</span></tt>.</p>
212</div>
213<div class="section" id="clonability">
214<h1><a name="clonability">Clonability</a></h1>
215<p>In OO programming it is typical to prohibit copying of objects; the
216objects may sometimes be allowed to be clonable; for example,:</p>
217<pre class="literal-block">
218animal* animal::clone() const
219{
220    return do_clone(); // implemented by private virtual function
221}
222</pre>
223<p>If the OO hierarchy thus allows cloning, we need to tell the
224pointer containers how cloning is to be done. This is simply
225done by defining a free-standing function, <tt class="docutils literal"><span class="pre">new_clone()</span></tt>,
226in the same namespace as
227the object hierarchy:</p>
228<pre class="literal-block">
229inline animal* new_clone( const animal&amp; a )
230{
231    return a.clone();
232}
233</pre>
234<p>That is all, now a lot of functions in a pointer container
235can exploit the clonability of the animal objects. For example</p>
236<pre class="literal-block">
237typedef boost::ptr_list&lt;animal&gt; zoo_type;
238zoo_type zoo, another_zoo;
239...
240another_zoo.assign( zoo.begin(), zoo.end() );
241</pre>
242<p>will fill another zoo with clones of the first zoo. Similarly,
243insert() can now insert clones into your pointer container</p>
244<pre class="literal-block">
245another_zoo.insert( another_zoo.begin(), zoo.begin(), zoo.end() );
246</pre>
247<p>The whole container can now also be cloned</p>
248<pre class="literal-block">
249zoo_type yet_another_zoo = zoo.clone();
250</pre>
251</div>
252<div class="section" id="new-functions">
253<h1><a name="new-functions">New functions</a></h1>
254<p>Given that we know we are working with pointers, a few new functions
255make sense. For example, say you want to remove an
256animal from the zoo</p>
257<pre class="literal-block">
258zoo_type::auto_type the_animal = zoo.release( zoo.begin() );
259the_animal-&gt;eat();
260animal* the_animal_ptr = the_animal.release(); // now this is not deleted
261zoo.release(2); // for random access containers
262</pre>
263<p>You can think of <tt class="docutils literal"><span class="pre">auto_type</span></tt> as a non-copyable form of
264<tt class="docutils literal"><span class="pre">std::auto_ptr</span></tt>. Notice that when you release an object, the
265pointer is removed from the container and the containers size
266shrinks. You can also release the entire container if you
267want to return it from a function</p>
268<pre class="literal-block">
269std::auto_ptr&lt; boost::ptr_deque&lt;animal&gt; &gt; get_zoo()
270{
271    boost::ptr_deque&lt;animal&gt;  result;
272    ...
273    return result.release(); // give up ownership
274}
275...
276boost::ptr_deque&lt;animal&gt; animals = get_zoo();   
277</pre>
278<p>Let us assume we want to move an animal object from
279one zoo to another. In other words, we want to move the
280animal and the responsibility of it to another zoo</p>
281<pre class="literal-block">
282another_zoo.transfer( another_zoo.end(), // insert before end
283                      zoo.begin(),       // insert this animal ...
284                      zoo );             // from this container
285</pre>
286<p>This kind of &quot;move-semantics&quot; is different from
287normal value-based containers. You can think of <tt class="docutils literal"><span class="pre">transfer()</span></tt>
288as the same as <tt class="docutils literal"><span class="pre">splice()</span></tt> on <tt class="docutils literal"><span class="pre">std::list</span></tt>.</p>
289<p>If you want to replace an element, you can easily do so</p>
290<pre class="literal-block">
291zoo_type::auto_type old_animal = zoo.replace( zoo.begin(), new monkey(&quot;bibi&quot;) );
292zoo.replace( 2, old_animal.release() ); // for random access containers
293</pre>
294<p>A map is a little different to iterator over than standard maps.
295Now we say</p>
296<pre class="literal-block">
297typedef boost::ptr_map&lt;std::string, boost::nullable&lt;animal&gt; &gt; animal_map;
298animal_map map;
299...
300for( animal_map::iterator i = map.begin();
301     i != map.end(); ++i )
302{
303    std::cout &lt;&lt; &quot;\n key: &quot; &lt;&lt; i.key();
304    std::cout &lt;&lt; &quot;\n age: &quot;;
305   
306    if( boost::is_null(i) )
307        std::cout &lt;&lt; &quot;unknown&quot;;
308    else
309        std::cout &lt;&lt; i-&gt;age();
310 }
311</pre>
312<p>Maps can also be indexed with bounds-checking</p>
313<pre class="literal-block">
314try
315{
316    animal&amp; bobo = map.at(&quot;bobo&quot;);
317}
318catch( boost::bad_ptr_container_operation&amp; e )
319{
320    // &quot;bobo&quot; not found
321}       
322</pre>
323</div>
324<div class="section" id="algorithms">
325<h1><a name="algorithms">Algorithms</a></h1>
326<p>Unfortunately it is not possible to use pointer containers with
327mutating algorithms from the standard library. However,
328the most useful ones
329are instead provided as member functions:</p>
330<pre class="literal-block">
331boost::ptr_vector&lt;animal&gt; zoo;
332...
333zoo.sort();                               // assume 'bool operator&lt;( const animal&amp;, const animal&amp; )'
334zoo.sort( std::less&lt;animal&gt;() );          // the same, notice no '*' is present
335zoo.sort( zoo.begin(), zoo.begin() + 5 ); // sort selected range
336</pre>
337<p>Notice that predicates are automatically wrapped in an <a class="reference" href="indirect_fun.html">indirect_fun</a> object.</p>
338<p>You can remove equal and adjacent elements using <tt class="docutils literal"><span class="pre">unique()</span></tt>:</p>
339<pre class="literal-block">
340zoo.unique();                             // assume 'bool operator==( const animal&amp;, const animal&amp; )'
341zoo.unique( zoo.begin(), zoo.begin() + 5, my_comparison_predicate() );
342</pre>
343<p>If you just want to remove certain elements, use <tt class="docutils literal"><span class="pre">erase_if</span></tt>:</p>
344<pre class="literal-block">
345zoo.erase_if( my_predicate() );
346</pre>
347<p>Finally you may want to merge together two sorted containers:</p>
348<pre class="literal-block">
349boost::ptr_vector&lt;animal&gt; another_zoo = ...;
350another_zoo.sort();                      // sorted wrt. to same order as 'zoo'
351zoo.merge( another_zoo );
352BOOST_ASSERT( another_zoo.empty() );   
353</pre>
354<p>That is all; now you have learned all the basics!</p>
355<p><strong>Navigate</strong></p>
356<blockquote>
357<ul class="simple">
358<li><a class="reference" href="ptr_container.html">home</a></li>
359<li><a class="reference" href="examples.html">examples</a></li>
360</ul>
361</blockquote>
362<table class="docutils field-list" frame="void" rules="none">
363<col class="field-name" />
364<col class="field-body" />
365<tbody valign="top">
366<tr class="field"><th class="field-name">copyright:</th><td class="field-body">Thorsten Ottosen 2004-2005.</td>
367</tr>
368</tbody>
369</table>
370</div>
371</div>
372</body>
373</html>
Note: See TracBrowser for help on using the repository browser.