3.3 Classes in C++ 77
{
T*A;
intlength;
public:
...
T&operator() (inti){returnA[i-1];}
...
};
In a code which uses this class we could declare various vectors as Declarations in user code:
Vector
Vector
where the first variable is double vector with ten elements while the second is an integer
vector with five elements.
Summarizing, it is easy to use the classVectorand we can hide in the class many details
which are visible in C and Fortran 77 codes. However, as you may have noted it is not easy
to write classVector. One ends often up with using ready-made classes in C++ libraries
such as Blitz++ or Armadillo unless you really need to develop your own code. Furthermore,
our vector class has served mainly a pedagogical scope, since C++ has a Standard Template
Library (STL) with vector types, including a vector for doing numerics that can be declared
as
std::valarray
However, there is no STL for a matrix type. We end therefore with recommending the use
of ready-made libraries like Blitz++ or Armadillo or the matrix class discussed in the linear
algebra chapter, see chapter 6.
We end this section by listing the final vector class, with both header file and the definitions
of the various functions. The major part of the listing belowis obvious and is not commented.
The usage of the class could be as follows:
Vector v1;
// Redimension the vector to have length n:
intn1 = 3;
v1.redim(n1);
cout <<"v1.getlength: "<< v1.getLength() << endl;
// Extract the length of the vector:
const intlength = v1.getLength();
// Create a vector of a specific length:
intn2 = 5;
Vector v2(n2);
cout <<"v2.getlength: "<< v2.getLength() << endl;
// Create a vector from an existing array:
intn3 = 3;
double*array =new double[n3];
Vector v4(n3, array);
cout <<"v4.getlength: "<< v4.getLength() << endl;
// Create a vector as a copy of another one:
Vector v5(v1);
cout <<"v5.getlength: "<< v5.getLength() << endl;
// Assign the entries in a vector:
v5(0) = 3.0;// or alternatively v5[0] = 3.0;