valarray可能大家都不是很熟悉,下面简单介绍一下:(下表是常用函数,跟cmath类似)
1valarray在valarray头文件里,下面是valarray的构造与输出
#include<iostream>
#include<string>
#include<valarray>
using namespace std;
int main(){
int a[]={1,2,3,4,5,6,7,8,9,10};
valarray<int>val(a,10);
val[4]=10086;
for(int i=0;i<10;++i){
cout<<val[i]<<" ";
}
cout<<endl;
valarray<int>vv(10);
vv=val;
for(int j=0;j<10;++j){
cout<<vv[j]<<" ";
}
cout<<endl;
system("pause");
return 0;
}
2几个valarray常用的函数
#include<iostream>
#include<valarray>
#include<string>
using namespace std;
int main(){
int a[]={1,2,3,4,5,6,7,8,9,10};
valarray<int>su(a,10);
for(int i=0;i<10;++i){
cout<<su[i]<<" ";
}
cout<<endl;
cout<<su.max()<<endl;
cout<<su.min()<<endl;
cout<<su.sum()<<endl;
system("pause");
return 0;
}
apply函数
#include<iostream>
#include<string>
#include<valarray>
using namespace std;
int jiayi(int a){
return ++a;
}
int main(){
int a[]={10,20,30,40,50,60,70,80,90,100};
valarray<int>v1(a,10);
valarray<int>v2=v1.apply(jiayi);
for(int i=0;i<10;++i){
cout<<v2[i]<<" ";
}
cout<<endl;
system("pause");
return 0;
}
shift(+)左移,shift(-)右移,非循环移动,用0来填补
#include<iostream>
#include<string>
#include<valarray>
using namespace std;
int main(){
int a[]={10,20,30,40,50};
valarray<int>val(a,5);
valarray<int>va;
int i;
for(i=0;i<5;++i){
cout<<val[i]<<" ";
}
cout<<endl;
va=val.shift(2);
for(i=0;i<5;++i){
cout<<va[i]<<" ";
}
cout<<endl;
va=val.shift(-2);
for(i=0;i<5;++i){
cout<<va[i]<<" ";
}
cout<<endl;
system("pause");
return 0;
}
cshift(+)左移,cshift(-)右移,循环移动
#include<iostream>
#include<string>
#include<valarray>
using namespace std;
int main(){
int a[]={10,20,30,40,50};
valarray<int>val(a,5);
valarray<int>va;
va=val.cshift(2);
for(int i=0;i<5;++i){
cout<<va[i]<<" ";
}
cout<<endl;
va=val.cshift(-2);
for(int j=0;j<5;++j){
cout<<va[j]<<" ";
}
cout<<endl;
system("pause");
return 0;
}
绝对值
#include<iostream>
#include<string>
#include<valarray>
using namespace std;
int main(){
int a[]={10,-5,2,-3,7};
valarray<int>v(a,5);
for(int i=0;i<5;++i){
cout<<v[i]<<" ";
}
cout<<endl;
valarray<int>vv=abs(v);
for(int j=0;j<5;++j){
cout<<vv[j]<<" ";
}
cout<<endl;
system("pause");
return 0;
}
slice切割函数,第一个参数是开始地址,第二个参数是元素个数,第三个参数是步长
#include<iostream>
#include<string>
#include<valarray>
using namespace std;
int main(){
int a[]={1,2,3,4,5,6,7,8,9,10,11,12};
valarray<int>v(a,12);
valarray<int>vv=v[slice(2,3,4)];
cout<<"slice(2,3,4)"<<endl;
for(int i=0;i<vv.size();++i){
cout<<vv[i]<<" ";
}
cout<<endl;
system("pause");
return 0;
}