zoukankan      html  css  js  c++  java
  • C++ transform

    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 }
  • 相关阅读:
    51nod 1087 1 10 100 1000(找规律+递推+stl)
    51nod 1082 与7无关的数 (打表预处理)
    51 nod 1080 两个数的平方和
    1015 水仙花数(水题)
    51 nod 1003 阶乘后面0的数量
    51nod 1002 数塔取数问题
    51 nod 1001 数组中和等于K的数对
    51 nod 1081 子段求和
    51nod 1134 最长递增子序列 (O(nlogn)算法)
    51nod 1174 区间中最大的数(RMQ)
  • 原文地址:https://www.cnblogs.com/balingybj/p/4678880.html
Copyright © 2011-2022 走看看