STL 之for_each,transform

for_each:对指定区间中的每个元素使用指定的函数进行访问及处理,所用的函数作为参数传递给该函数。

transform:元素传输


声明:

  1. #include <algorithm>  
  2. template <class inputItr,class function>  
  3. function for_each(inputItr first,inputItr last,function func);  
  4.   
  5. template <class inputItr, class outputItr, class unaryOperation>  
  6. outputItr transform(inputItr first,inputItr last, outputItr destFirst,unaryOperation op);  
  7.   
  8. template <class inputItr1, class inputItr2, class outputItr, class binaryOperation>  
  9. outputItr transform(inputItr1 first1, inputItr1 last, inputItr2 first2, outputItr destFirst,binaryOperation bop);  

示例代码:

  1. #include <iostream>  
  2. #include <list>  
  3.   
  4. #include <string>  
  5. #include <numeric>  
  6. #include <iterator>  
  7. #include <vector>  
  8. #include <functional>  
  9.   
  10. #include <algorithm>  
  11.   
  12. using namespace std;  
  13.   
  14. void doubleNum(int& num) {  
  15.     num = 2 * num;  
  16.     cout << num << " ";  
  17. }  
  18.   
  19. int main() {  
  20.     char cList[5] = {'a','b','c','d','e'};  
  21.     vector<char> charList(cList,cList+5);  
  22.     ostream_iterator<char> sreen(cout, " ");  
  23.   
  24.     cout << "charList:" << endl;  
  25.     copy(charList.begin(),charList.end(),sreen);  
  26.     cout << endl;  
  27.   
  28.     //transform  
  29.     transform(charList.begin(),charList.end(),charList.begin(),toupper);  
  30.     cout << "charList:" << endl;  
  31.     copy(charList.begin(),charList.end(),sreen);  
  32.     cout << endl;  
  33.   
  34.     int list[7] = {2,8,5,1,7,11,3};  
  35.     ostream_iterator<int> srceenInt(cout, " ");  
  36.     cout << "list" << endl;  
  37.     copy(list,list+7,srceenInt);  
  38.     cout << endl;  
  39.   
  40.     // for_each  
  41.     for_each(list,list + 7, doubleNum);  
  42.     cout << endl;  
  43.   
  44.     cout << "list" << endl;  
  45.     copy(list,list+7,srceenInt);  
  46.     cout << endl;  
  47.       
  48.     return 0;  
  49. }  

运行结果:

charList:
a b c d e
charList:
A B C D E
list
2 8 5 1 7 11 3
4 16 10 2 14 22 6
list
4 16 10 2 14 22 6

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值