You’ve seen this syntax before in Chapter 4, “Compound Types,” with the vector and array classes, and it’s pretty easy. (Those template classes also can hold numbers, but they don’t provide all the arithmetic support the valarray class does.)
The class aspect means that to use valarray objects, you need to know something about class constructors and other class methods. Here are several examples that use some of the constructors:
double gpa[5] = {3.1, 3.5, 3.8, 2.9, 3.3};
valarray
valarray
valarray
// each set to 10
valarray
// initialized to the first 4 elements of gpa
As you can see, you can create an empty array of zero size, an empty array of a given size, an array with all elements initialized to the same value, and an array initialized using the values from an ordinary array. With C++11, you also can use an initializer list:
valarray
Next, here are a few of the methods:
• The operator[]() method provides access to individual elements.
• The size() method returns the number of elements.
• The sum() method returns the sum of the elements.
• The max() method returns the largest element.
• The min() method returns the smallest element.
There are many more methods, some of which are presented in Chapter 16, but you’ve already seen more than enough to proceed with this example.
The Student Class Design
At this point, the design plan for the Student class is to use a string object to represent the name and a valarray
class Student
{
private:
string name; // use a string object for name
valarray
...
};