使用两个C++向量作为参数的“复杂”操作函数的最佳方法
为了简单起见,请问用以下 Python 代码在 C++ 中编写以下代码的最佳方法是什么
import numpy as np
X = np.array([1,2,3,...])
Y = np.array([10,11,12,...])
def funct(X,Y):
return 0.5 * X + 0.5 * 3 * Y
或者,在没有 Python 的情况下进行解释,有没有办法:
#include <vector>
std::vector<double> Z {};
std::vector<double> X {1,2,3,4};
std::vector<double> Y {5,6,7,8};
Z = 0.5 * X + 0.5 * 3 * Y; // something like this
回答
也许valarray是你需要的:
#include <iostream>
#include <valarray>
int main() {
std::valarray<double> Z {};
std::valarray<double> X {1,2,3,4};
std::valarray<double> Y {5,6,7,8};
Z = 0.5 * X + 0.5 * 3 * Y;
for(auto v : Z) std::cout << v << 'n';
}
输出
8
10
12
14
请注意std::valarray:“当两个参数是大小不同的 valarray 时,行为未定义。 ”
- Great to see a suggestion to use valarray! I rarely see it being used. It's really old, but how mature is it? I mean, is it properly supported by optimizers? Last time I tried to use a vallarray in ms vs2019, it turned out it was actually broken in the ms stl (its fixed now).
- OK, found my mistake. Wrong constructor for std::valarray. Anyhow, [it would seen that valarray is 3.3x faster then vector/algo](https://quick-bench.com/q/G3X-qT_QMz--r8aGrTbMA6LlmKM) . But as valarray uses expression trees, I'm not sure thats actually the case. [I did a second bench where I accumulate the output](https://quick-bench.com/q/GFMW0tUmkmThxv3s3VbTgITkpNk), which gives a different result (~1.5x) but the accumulate is also in the bench loop, so the bench is not isolated. Still valarray seems faster! noice!