Information Technology Reference
In-Depth Information
std::valarray<double> u(n+1);
The u array is automatically deleted when it is no longer in use. The declaration of
arrays of type valarray in a function such as heun is as follows:
void heun (fptr f, double u0, double dt, int n,
std::valarray<double>& u)
The ampersand & indicates that a reference to the u object is transferred; without
the ampersand, u will be a copy of the transferred array. This is not what we want,
since our goal is to compute values in u and view these values outside the heun
function. The syntax of the body of the heun function is independent of whether we
use std::valarray or plain C/C CC arrays.
Multi-dimensional arrays in C and C CC can be constructed, but the allocation
and use of new is more complicated. Details can be found in topics on the C or C CC
programming language. Unfortunately, the standard C CC library does not offer a
class such as valarray for multi-dimensional arrays. One can, nevertheless, create
a class for multi-dimensional arrays with minor effort. There are also several open
source and commercial libraries in C CC that offer sophisticated multi-dimensional
arrays for numerical computing.
File Writing
Basic file writing in C CC is illustrated next 14 :
std::ofstream out("sol.dat"); // open a file sol.dat
out << "some text " << object << " more text\n";
out.close()
A dump function for writing the u .t / values to a file can typically be coded as
follows:
void dump (std::ostream& out, double u[], int n, double t0, double dt)
{
double time = t0;
for (int i = 0; i <= n; i++) {
out << time << " " << u[i] << '\n';
time += dt;
}
}
Although the file is of type std::ofstream , it is common to declare the corre-
sponding function argument as std::ostream , because this type is a common name
for all types of output media. For example, the out argument above can be a file
( std::ofstream ) or the terminal window ( std::cout ), or even a string.
14 This is C
file writing. One can also use the C functionality for file writing. This can be
convenient if format control via the fprintf function is desired.
CC
Search WWH ::




Custom Search