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.

2.9. ARRAYS 49<br />

• : Complex numbers<br />

• , , , , ...: STL, see Section 4.9<br />

Inline keyword<br />

Instead of creating a library as described at the beginning of this section, we can also store the<br />

implementation in the header file. We then have to add the keyword inline <strong>for</strong> two reasons. The<br />

code will not be stored in a library but inlined in the calling functions: this may lead to more<br />

efficient code when the functions are small. If we do not use the inline keyword, we may end<br />

up with multiple defined functions, since the compiler will create the methods in every source<br />

file they are used.<br />

Consider <strong>for</strong> example the following header file sqr.hpp:<br />

#ifndef athens sqr hpp<br />

#define athens sqr hpp<br />

inline double sqr(double a)<br />

{ return a∗a;}<br />

#endif<br />

2.9 Arrays<br />

C based programming languages are not very good at working with arrays. In this section, we<br />

discuss the language concepts <strong>for</strong> arrays. In Section 4.9, we will present more practical software<br />

<strong>for</strong> arrays and other complicated mass data structures.<br />

An array is created as follow<br />

int x[10];<br />

The variable x is a constant size array. It allows <strong>for</strong> fast creation (it is typically stored on the<br />

stack).<br />

Arrays are accessed by square brackets: x[i] is a reference to the ith element. The first element<br />

is x[0], the last one is x[9]. Arrays can be initialized at the definition<br />

float v[]= {1.0, 2.0, 3.0}, w[]= {7.0, 8.0, 9.0};<br />

In this case, the array size is deduced.<br />

Operations on arrays are typically per<strong>for</strong>med in loops, e.g. to compute x = v − 3w as vector<br />

operation is realized by<br />

float x[3];<br />

<strong>for</strong> (int i= 0; i < 3; i++)<br />

x[i]= v[i] − 3.0 ∗ w[i];<br />

One can also define arrays of higher dimension

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

Saved successfully!

Ooh no, something went wrong!