C ++中的元素操作 [英] Element-wise operations in C++
问题描述
是否有一个预先存在的库,将允许我创建具有以下属性的数组类对象:
Is there a preexisting library that will let me create array-like objects which have the following properties:
- 运行时间大小规格
- 重载执行元素操作的运算符(即
c = a + b
在中的
,同样c
与c [i] = a [i] + b [i]
$ c> i*
,-
,/ c>等)
- 一组很好的元素操作函数,例如
x = sqrt(vec)
将有x [i] = sqrt(vec [i])
- 提供汇总 code> sum(vec),
mean(vec)
等 - 可以发送到GPU进行处理。
- 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 vectorc
withc[i]=a[i]+b[i]
for alli
, and similarly for*
,-
,/
, etc) - A good set of functions which act elementwise, for example
x=sqrt(vec)
will have elementsx[i]=sqrt(vec[i])
- Provide "summarising" functions such as
sum(vec)
,mean(vec)
etc - (Optional) Operations can be sent to a GPU for processing.
基本上类似于数组在Fortran中工作的方式,所有的实现都隐藏。目前我使用向量
从STL和手动重载操作符,但我觉得这可能是一个解决的问题。
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.
推荐答案
在标准库的尘土飞扬的角落里,每个人都忘记了,坐在一个名为 valarray
查找它是否适合您的需要。
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.
std :: valarray
是表示和操作值数组的类。它支持元素级数学运算和各种形式的广义下标运算符,切片和间接访问。
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.
用于说明的代码段:
#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, " "));
}
输出: 2 4 6 8 10
这篇关于C ++中的元素操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!