C++中transform()函数用法及tolower()大小写转化
C++之transform 函数用法
- 介绍
- 函数
- Example 1
- Example 2
- Reference
介绍
transform函数的作用是:将某操作应用于指定范围的每个元素。
函数
格式:transform(first,last,result,op);
- first是容器的首迭代器
- last为容器的末迭代器
- result为存放结果的容器
- op为要进行操作的一元函数对象或sturct、class。
Example 1
利用transform函数将一个给定的字符串中的小写字母改写成大写字母,并将结果保存在一个叫second的数组里,原字符串内容不变。
#include
#include
using namespace std;
char op(char ch)
{if(ch>='A'&&ch<='Z')return ch+32;elsereturn ch;
}
int main()
{string first,second;cin>>first;second.resize(first.size());transform(first.begin(),first.end(),second.begin(),op);cout<<second<<endl;return 0;
}
C++中有两个函数可进行快速变换大小写,tolower()函数是把字符串都转化为小写字母;touppre()函数是把字符串都转化为大写字母。故上述代码中transform函数可写为:
transform(first.begin(),first.end(),second.begin(),::tolower);
C++中没有提供string类型的大小写转换,也可以:
s[i]+32 or s[i]-32
#include
using namespace std;int main() {char s[100];gets(s);for(int i = 0; i < sizeof(s); i++) {s[i] = tolower(s[i]);}cout << s;
}
Example 2
给你两个vector向量(元素个数相等),请你利用transform函数将两个vector的每个元素相乘,并输出相乘的结果。
// 两个vector对位相乘
int op(int a,int b){return a*b;}
int main(){vector <int> A,B,SUM;int n;cin>>n;for(int i=0;i<n;i++){int t;cin>>t;A.push_back(t);}for(int i=0;i<n;i++){int t;cin>>t;B.push_back(t);}SUM.resize(n);transform(A.begin(),A.end(),B.begin(),SUM.begin(),op);for (auto n : SUM){cout << n;}return 0;}
Reference
Link
Link
加油!
感谢!
努力!
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
