Is there a preexisting library that will let me create array-like objects which have the following properties:
c=a+b
will result in a vector c
with c[i]=a[i]+b[i]
for all i
, and similarly for *
, -
, /
, etc)x=sqrt(vec)
will have elements x[i]=sqrt(vec[i])
sum(vec)
, mean(vec)
etcBasically 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.
An element-wise operation is an operation between two tensors that operates on corresponding elements within the respective tensors. An element-wise operation operates on corresponding elements between tensors. Two elements are said to be corresponding if the two elements occupy the same position within the tensor.
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
You can use Cilk Plus Extentions (https://www.cilkplus.org/) that provides array notation by applying element-wise operations to arrays of the same shape for C/C++. It explores the vector parallelism from your processor as well co-processor.
Example: Standard C code:
for (i=0; i<MAX; i++)
c[i]=a[i]+b[i];
Cilk Plus - Array notation:
c[i:MAX]=a[i:MAX]+b[i:MAX];
Stride sections like:
float d[10] = {0,1,2,3,4,5,6,7,8,9};
float x[3];
x[:] = d[0:3:2]; //x contains 0,2,4 values
You can use reductions on arrays sections:
_sec_reduce_add(a[0:n]);
Interest reading: http://software.intel.com/en-us/articles/getting-started-with-intel-cilk-plus-array-notations
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With