03.12.2012 Views

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

130 CHAPTER 4. GENERIC PROGRAMMING<br />

Create a meta function to check whether a type is a pointer. Write a function evaluate that<br />

returns the same value as its argument, except when the argument is a pointer, in which case<br />

you return the value pointed to by the pointer. Hint: look at http://www.boost.org/libs/<br />

utility/enable_if.html <strong>for</strong> enable if c.<br />

4.11.7 Meta-list<br />

Revisit exercise ??.<br />

Make a list of types. Make meta functions insert, append, delete and size.<br />

4.11.8 Iterator of a vector<br />

Revisit exercise ??. Add methods begin() and end() <strong>for</strong> returning a begin and end iterator. Add<br />

the types iterator and const iterator to the class. Note that pointers are iterators.<br />

Use the STL functions sort and lower bound.<br />

4.11.9 Iterator of a list<br />

Revisit exercise ??.<br />

Make a generic list type.<br />

Add methods begin() and end() <strong>for</strong> returning a begin and end const iterator. Add the type<br />

const iterator to the class. Note that pointers cannot be used as iterators.<br />

4.11.10 Trapezoid rule<br />

A simple method <strong>for</strong> computing the integral of a function is the trapezoid rule. Suppose we<br />

want to integrate the function f over the interval [a, b]. We split the interval in n small intervals<br />

[xi, xi+1] of the same length h = (b − a)/n and approximate f by a piecewise linear function.<br />

The integral is then approximated by the sum of the integrals of the piecewise linear function.<br />

This gives us the <strong>for</strong>mula :<br />

I = h<br />

2<br />

f(a) + h<br />

2<br />

n−1 �<br />

f(b) + h<br />

j=1<br />

f(a + jh) (4.1)<br />

In this exercise, we develop a function <strong>for</strong> the trapezoid rule, with a functor argument. We<br />

develop software using inheritance and using generic programming. Then we use the function<br />

<strong>for</strong> integrating the following functions:<br />

• f = exp(−3x) <strong>for</strong> x ∈ [0, 4]. Try the following arguments of trapezoid:<br />

double exp3( double x ) {<br />

return std::exp( 3.0 ∗ x ) ;<br />

}<br />

struct exp3 {

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!