C ++中的元素操作 [英] Element-wise operations in C++

查看:184
本文介绍了C ++中的元素操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个预先存在的库,将允许我创建具有以下属性的数组类对象:

Is there a preexisting library that will let me create array-like objects which have the following properties:


  1. 运行时间大小规格

  2. 重载执行元素操作的运算符(即 c = a + b 中的 c c [i] = a [i] + b [i] $ c> i ,同样 * - / c>等)

  3. 一组很好的元素操作函数,例如 x = sqrt(vec)将有 x [i] = sqrt(vec [i])

  4. 提供汇总 code> sum(vec) mean(vec)

  5. 可以发送到GPU进行处理。

  1. Run time size specification (chosen at instantition, not grown or shrunk afterwards)
  2. 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)
  3. A good set of functions which act elementwise, for example x=sqrt(vec) will have elements x[i]=sqrt(vec[i])
  4. Provide "summarising" functions such as sum(vec), mean(vec) etc
  5. (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.

手动页面位于cppreference.com


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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆