首先看一下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