std::valarray
valarray†
数値計算用の配列.element-wiseな計算ができる.
たとえば,値が入った二つの配列 a[10], b[10] を要素ごとに足した結果を配列 c[10] に格納したい場合,
valarrayを使わない場合は,
for(int i = 0; i < 10; ++i) c[i] = a[i]+b[i];
となるが,valarrayを使った場合,
c = a+b
でよい.absやexp,sin,cosといったcmathで定義されている数学関数に関してもオーバーロード関数が用意されている.
そのほか,sumやmin,max,shiftなどのメンバ関数もある.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
| | template<typename T>
inline std::ostream &operator<<(std::ostream &out, const valarray<T> &x)
{
for(size_t i = 0; i < x.size(); ++i){
out << x[i] << (i == x.size()-1 ? "" : ", ");
}
return out;
}
int main(void)
{
double val[] = {1.0, 2.0, 3.0, 4.0};
valarray<double> x(val, 4);
valarray<double> y(3.0, 4);
cout << "x = " << x << endl;
cout << "y = " << y << endl;
cout << "2*y+x = " << 2.0*y+x << endl;
cout << "exp(x) = " << exp(x) << endl;
cout << "sin(x) = " << sin(x) << endl;
cout << "max(x) = " << x.max() << endl;
cout << "min(x) = " << x.min() << endl;
cout << "sum(x) = " << x.sum() << endl;
cout << "cshift(x, 2) = " << x.cshift(2) << endl;
cout << "cshift(x, -1) = " << x.cshift(-1) << endl;
cout << "shift(x, 2) = " << x.shift(2) << endl;
cout << "shift(x, -1) = " << x.shift(-1) << endl;
cout << "pow(x, 2) = " << pow(x, 2.0) << endl;
cout << "pow(2, x) = " << pow(2.0, x) << endl;
return 0;
}
|
実行結果は,
x = 1, 2, 3, 4
y = 3, 3, 3, 3
2*y+x = 7, 8, 9, 10
exp(x) = 2.71828, 7.38906, 20.0855, 54.5982
sin(x) = 0.841471, 0.909297, 0.14112, -0.756802
max(x) = 4
min(x) = 1
sum(x) = 10
cshift(x, 2) = 3, 4, 1, 2
cshift(x, -1) = 4, 1, 2, 3
shift(x, 2) = 3, 4, 0, 0
shift(x, -1) = 0, 1, 2, 3
pow(x, 2) = 1, 4, 9, 16
pow(2, x) = 2, 4, 8, 16