Back to C++
2026-03-138 min read

valarray (C++)

Learn valarray (C++) step by step with clear examples and exercises.

Why This Matters

In C++ programming, dealing with arrays can be a bit tricky due to their static size. However, the std::valarray class provides a solution for this issue by offering a dynamic array that supports various mathematical operations. Understanding and using std::valarray can help you write more efficient code, especially when dealing with numerical computations and data analysis tasks.

When working with large datasets or performing complex calculations, static arrays might not be the best choice due to their fixed size. This is where std::valarray shines, as it allows for dynamic array creation and supports various mathematical operations, making it ideal for numerical computations.

Prerequisites

Before diving into the std::valarray, make sure you have a good understanding of the following concepts:

  1. C++ basics: variables, functions, classes, and objects
  2. Arrays in C++: static arrays and their limitations
  3. Standard Template Library (STL): containers, iterators, and algorithms
  4. Basic mathematical operations in C++
  5. Understanding of data structures like vectors and matrices
  6. Familiarity with concepts such as loops, functions, and templates

Core Concept

std::valarray is a template class from the Standard Template Library (STL) in C++ that provides an array-like container for numerical data. It supports various mathematical operations such as addition, subtraction, multiplication, and division, making it ideal for numerical computations.

std::valarray is a dynamic array that can be resized dynamically using the resize() function. This means you don't have to worry about preallocating memory or dealing with array bounds when working with large datasets.

Creating a std::valarray

To create a std::valarray, you need to specify the element type in angle brackets (< >) followed by the size of the array in parentheses. Here's an example:

#include <valarray>

int main() {
std::valarray<double> myArray(5); // creates a valarray of 5 double elements, all initialized to zero
}

You can also initialize the std::valarray with specific values. For example:

#include <valarray>
#include <iostream>

int main() {
std::valarray<double> myArray = {1.0, 2.0, 3.0, 4.0, 5.0}; // creates a valarray with the specified values
std::cout << "Initial array: ";
for (int i = 0; i < myArray.size(); ++i) {
std::cout << myArray[i] << ' ';
}
std::cout << '\n';
}

Mathematical Operations

std::valarray supports various mathematical operations, including addition, subtraction, multiplication, and division. Here's an example demonstrating these operations:

#include <valarray>
#include <iostream>

int main() {
std::valarray<double> a = {1.0, 2.0, 3.0, 4.0, 5.0};
std::valarray<double> b = {6.0, 7.0, 8.0, 9.0, 10.0};

std::valarray<double> result_add = a + b; // addition
std::valarray<double> result_sub = a - b; // subtraction
std::valarray<double> result_mul = a * b; // multiplication
std::valarray<double> result_div = a / b; // division

std::cout << "Addition: ";
for (int i = 0; i < result_add.size(); ++i) {
std::cout << result_add[i] << ' ';
}
std::cout << '\n';

std::cout << "Subtraction: ";
for (int i = 0; i < result_sub.size(); ++i) {
std::cout << result_sub[i] << ' ';
}
std::cout << '\n';

std::cout << "Multiplication: ";
for (int i = 0; i < result_mul.size(); ++i) {
std::cout << result_mul[i] << ' ';
}
std::cout << '\n';

std::cout << "Division: ";
for (int i = 0; i < result_div.size(); ++i) {
std::cout << result_div[i] << ' ';
}
std::cout << '\n';
}

Other Useful Functions

In addition to mathematical operations, std::valarray offers several other functions that can be useful in various scenarios. Some of these functions include:

  • size(): returns the number of elements in the array
  • resize(n): resizes the array to contain n elements
  • sum(): calculates the sum of all elements in the array
  • min_element() and max_element(): return pointers to the minimum and maximum elements, respectively
  • sort(): sorts the elements in ascending order
  • reduce(binary_function f): applies a binary function (e.g., addition, multiplication) to all elements in the array and returns the result

Worked Example

Let's work through an example that demonstrates using std::valarray for numerical computations. In this example, we will calculate the average of a set of numbers and find the maximum and minimum values.

#include <iostream>
#include <valarray>

int main() {
std::valarray<double> numbers = {1.2, 3.5, 6.7, 8.9, 10.0};

double average = numbers.sum() / numbers.size();
double max_value = *numbers.max_element();
double min_value = *numbers.min_element();

std::cout << "Average: " << average << '\n';
std::cout << "Maximum value: " << max_value << '\n';
std::cout << "Minimum value: " << min_value << '\n';
}

Common Mistakes

  1. Forgetting to include the `` header.
  2. Trying to use std::valarray with non-numeric types (e.g., strings or pointers).
  3. Not understanding the difference between std::vector and std::valarray. While both are containers, std::valarray is designed for numerical computations and supports mathematical operations.
  4. Failing to initialize the std::valarray with specific values when creating it without a size.
  5. Assuming that all elements in the array will be initialized to the same value (e.g., zero) if no initializer list is provided.
  6. Not using the appropriate function for the desired operation, such as using sum() instead of reduce(std::plus{}).
  7. Not handling exceptions when performing mathematical operations that might result in errors (e.g., division by zero).
  8. Failing to deallocate memory when resizing the array, which can lead to memory leaks.
  9. Using the wrong order of arguments for functions like sum(), which expects the first argument to be a binary function (even though it is not used in this case).

Practice Questions

  1. Write a program that creates a std::valarray of 10 random numbers between 0 and 100, calculates their average, and finds the maximum and minimum values.
  2. Create a program that sorts a std::valarray of integers using the sort() function and prints the sorted array.
  3. Write a program that uses std::valarray to perform matrix multiplication (assuming both matrices have the same number of columns).
  4. Implement a function that finds the second maximum value in a std::valarray of integers using the max_element() and size() functions.
  5. Write a program that calculates the standard deviation of a set of numbers using a std::valarray.
  6. Write a program that finds the product of all elements in a std::valarray using the reduce(std::multiplies{}) function.
  7. Implement a function that finds the sum of the squares of all elements in a std::valarray using the reduce(std::pow()) function.
  8. Write a program that calculates the mean absolute deviation (MAD) of a set of numbers using a std::valarray.
  9. Implement a function that finds the median value in a sorted std::valarray of integers when the array has an odd number of elements.
  10. Write a program that calculates the variance of a set of numbers using a std::valarray.

FAQ

Q: Can I use std::valarray with non-numeric types like strings or pointers?

A: No, std::valarray is designed for numerical data only.

Q: What's the difference between std::vector and std::valarray?

A: While both are containers, std::valarray is optimized for numerical computations and supports mathematical operations, whereas std::vector is a general-purpose container that can store any type of data.

Q: Why don't all elements in my std::valarray get initialized to the same value when I create it without an initializer list?

A: When you create a std::valarray without an initializer list, it is filled with uninitialized values. To ensure that all elements are initialized to a specific value (e.g., zero), use an initializer list or set the values explicitly using loops or functions like fill().

Q: How can I find the second maximum value in a std::valarray of integers?

A: To find the second maximum value, first find the maximum value using the max_element() function, then iterate through the array and find the next maximum value (excluding the first one). You can use the next(begin(), index) function to access elements by their index.

Q: How do I calculate the standard deviation of a set of numbers using a std::valarray?

A: To calculate the standard deviation, first find the mean (average) of the numbers using the sum() and size() functions. Then, for each number subtract the mean, square the result, sum up these squared differences, divide by the number of elements minus one, and take the square root. You can use the reduce(std::pow()) function to calculate the sum of squared differences.

Q: How do I handle exceptions when performing mathematical operations that might result in errors (e.g., division by zero)?

A: To handle exceptions, you can wrap the operation in a try-catch block. For example, when dividing two arrays, check if either array has zero elements before performing the division to avoid exceptions.

Q: What happens if I resize the std::valarray without deallocating memory?

A: If you resize the std::valarray without deallocating memory, it can lead to memory leaks. To avoid this, use the clear() function before resizing or use smart pointers like std::unique_ptr or std::shared_ptr.

Q: Why does the sum() function expect a binary function as its first argument even though it is not used in the example?

A: The sum() function expects a binary function because it can be used to perform more complex calculations than simple addition, such as finding the sum of the squares or the product of elements. In this case, it is not necessary to provide a binary function since we are only performing simple addition.

Q: What is the mean absolute deviation (MAD) and how can I calculate it using a std::valarray?

A: The mean absolute deviation (MAD) is a measure of dispersion that calculates the average absolute difference between the data points and the median. To calculate MAD, first find the median value, then for each number subtract the median and take the absolute value. Finally, calculate the average of these absolute differences using the reduce(std::abs{}) function.

Q: How do I find the median value in a sorted std::valarray of integers when the array has an odd number of elements?

A: When the array has an odd number of elements, the median is simply the middle element. If you have already sorted the array, you can access the middle element using the formula (size - 1) / 2. If the size is even, you can take the average of the two middle elements.

valarray (C++) | C++ | XQA Learn