transform 转换大小写

首先看一下transform的原型

template < class InputIterator, class OutputIterator, class UnaryOperator >
  OutputIterator transform ( InputIterator first1, InputIterator last1,
                             OutputIterator result, UnaryOperator op );

template < class InputIterator1, class InputIterator2,
           class OutputIterator, class BinaryOperator >
  OutputIterator transform ( InputIterator1 first1, InputIterator1 last1,
                             InputIterator2 first2, OutputIterator result,
                             BinaryOperator binary_op );

上面两个函数重载版本

1  是对原[first1, last1)之间所有和类型T,调用一个一元函数 op,然后把结果输出到result

2 是对原[first1, last1)之间所有和类型T,加上另一个参数也是从first开始,调用一个二元函数 op,然后把结果输出到result

其内部实现如下

template <class _InputIter, class _OutputIter, class _UnaryOperation>//模板参数,指定迭代器类型
_STLP_INLINE_LOOP _OutputIter
transform(_InputIter __first, _InputIter __last, _OutputIter __result, _UnaryOperation __opr) {
  _STLP_DEBUG_CHECK(_STLP_PRIV __check_range(__first, __last))
  for ( ; __first != __last; ++__first, ++__result)
    *__result = __opr(*__first);//一元函数
  return __result;//最后得到指向未尾的指针
}
template <class _InputIter1, class _InputIter2, class _OutputIter, class _BinaryOperation>
_STLP_INLINE_LOOP _OutputIter
transform(_InputIter1 __first1, _InputIter1 __last1,
          _InputIter2 __first2, _OutputIter __result,_BinaryOperation __binary_op) {
  _STLP_DEBUG_CHECK(_STLP_PRIV __check_range(__first1, __last1))
  for ( ; __first1 != __last1; ++__first1, ++__first2, ++__result)
    *__result = __binary_op(*__first1, *__first2);//二元函数
  return __result;
}

函数调用读入每一行函数形式然后输出

#include <algorithm>
#include <cctype>
#include <iostream>
using std::cin;
using std::cout;
int main()
{
  std::string str;
  while(cin>>str){
    std::transform(str.begin(),str.end(),str.begin(),tolower);
    cout<<str;
   }
}

补充:另外一种调用函数如下:

vector<int> a;
vector<int> b;
for(int i=1;i<10;i++) a.push_back(i*10);// a 10 20 30 ...90
for(int i=1;i<10;i++) b.push_back(i*(-10)); //b -10 -20 ..-90

vector<int> c(10);//一定要先申请足够存放的空间
transorm(a.begin,a.end(),b.begin(),c.begin(),plus<int,int,int>()); // c 0 0 0 0 0 0 0 0 0

转载于:https://www.cnblogs.com/K-R-Q/archive/2011/10/24/2222692.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值