transform函數的作用是:將某操作應用於指定范圍的每個元素。transform函數有兩個重載版本:
transform(first,last,result,op);//first是容器的首迭代器,last為容器的末迭代器,result為存放結果的容器,op為要進行操作的一元函數對象或sturct、class。
transform(first1,last1,first2,result,binary_op);//first1是第一個容器的首迭代 器,last1為第一個容器的末迭代器,first2為第二個容器的首迭代器,result為存放結果的容器,binary_op為要進行操作的二元函數 對象或sturct、class。
注意:第二個重載版本必須要保證兩個容器的元素個數相等才行,否則會拋出異常。
看一個例子:利用transform函數將一個給定的字符串中的小寫字母改寫成大寫字母,並將結果保存在一個叫second的數組里,原字符串內容不變。
我們只需要使用transform的第一個重載函數,當然我們也可以使用for_each函數來完成再copy幾次就行了,現在來看一下代碼:
1 #include <iostream> 2 #include <algorithm> 3 using namespace std; 4 char op(char ch) 5 { 6 7 if(ch>='A'&&ch<='Z') 8 return ch+32; 9 else 10 return ch; 11 } 12 int main() 13 { 14 string first,second; 15 cin>>first; 16 second.resize(first.size()); 17 transform(first.begin(),first.end(),second.begin(),op); 18 cout<<second<<endl; 19 return 0; 20 }
再看一個例子:給你兩個vector向量(元素個數相等),請你利用transform函數將兩個vector的每個元素相乘,並輸出相乘的結果。
代碼:
foreach的用法
1 #include <iostream> 2 #include <algorithm> 3 #include <vector> 4 using namespace std; 5 void print(int &elem){cout<<elem<<" ";} 6 int op(int a,int b){return a*b;} 7 int main() 8 { 9 vector <int> A,B,SUM; 10 int n; 11 cin>>n; 12 for(int i=0;i<n;i++) 13 { 14 int t; 15 cin>>t; 16 A.push_back(t); 17 } 18 for(int i=0;i<n;i++) 19 { 20 int t; 21 cin>>t; 22 B.push_back(t); 23 } 24 SUM.resize(n); 25 transform(A.begin(),A.end(),B.begin(),SUM.begin(),op); 26 for_each(SUM.begin(),SUM.end(),print); 27 return 0; 28 }