The valarray Class: A Quick Look

The valarray class is supported by the valarray header file. As its name suggests, the class is targeted to deal with numeric values (or with classes with similar properties), so it supports operations such as summing the contents and finding the largest and smallest values in an array. So that it can handle different data types, valarray is defined as a template class. Later, this chapter goes into how to define template classes, but all you need to know now is how to use one.

The template aspect means that you have to provide a specific type when declaring an object. To do so when declaring an object, you follow the identifier valarray with angle brackets that contain the desired type:

valarray<int> q_values;     // an array of int
valarray<double> weights;   // an array of double

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<double> v1;         // an array of double, size 0
valarray<int> v2(8);         // an array of 8 int elements
valarray<int> v3(10,8);      // an array of 8 int elements,
                             // each set to 10
valarray<double> v4(gpa, 4); // an array of 4 elements
             // 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<int> v5 = {20, 32, 17, 9};  // C++11

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.136.233.153