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 }
原文链接: https://www.cnblogs.com/balingybj/p/4678880.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/219629
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!