Element-wise operations in C++

arrays, c++, fortran, gpu, vector

Solution

In the dusty corners of standard library, long forgotten by everyone, sits a class called `valarray`. Look it up and see if it suits your needs.

From manual page at cppreference.com:

`std::valarray` is the class for representing and manipulating arrays of values. It supports element-wise mathematical operations and various forms of generalized subscript operators, slicing and indirect access.

A code snippet for illustration:

#include <valarray>
#include <algorithm>
#include <iterator>
#include <iostream>

int main()
{
    std::valarray<int> a { 1, 2, 3, 4, 5};
    std::valarray<int> b = a;
    std::valarray<int> c = a + b;
    std::copy(begin(c), end(c),
        std::ostream_iterator<int>(std::cout, " "));
}

Output: `2 4 6 8 10`

Problem

Is there a preexisting library that will let me create array-like objects which have the following properties: - Run time size specification (chosen at instantition, not grown or shrunk afterwards) - Operators overloaded to perform element wise operations (i.e. `c=a+b` will result in a vector `c` with `c[i]=a[i]+b[i]` for all `i`, and similarly for `*`, `-`, `/`, etc) - A good set of functions which act elementwise, for example `x=sqrt(vec)` will have elements `x[i]=sqrt(vec[i])` - Provide "summarising" functions such as `sum(vec)`, `mean(vec)` etc - (Optional) Operations can be sent to a GPU for processing. Basically something like the way arrays work in Fortran, with all of the implementation hidden. Currently I am using `vector` from the STL and manually overloading the operators, but I feel like this is probably a solved problem.

Original source