transform使用详解

来源:互联网 发布:淘宝详情页怎么优化 编辑:程序博客网 时间:2024/05/22 12:06

文件原型及可能的实现:

版本一:

template<class InputIt, class OutputIt, class UnaryOperation>OutputIt transform(InputIt first1, InputIt last1, OutputIt d_first,  UnaryOperation unary_op){    while (first1 != last1) {        *d_first++ = unary_op(*first1++);    }    return d_first;}

first1last1范围内的元素执行一元操作unary_op后保存在d_first开始的位置。

版本二:

template<class InputIt1, class InputIt2,          class OutputIt, class BinaryOperation>OutputIt transform(InputIt1 first1, InputIt1 last1, InputIt2 first2, OutputIt d_first, BinaryOperation binary_op){    while (first1 != last1) {        *d_first++ = binary_op(*first1++, *first2++);    }    return d_first;}

first1last1first2二元操作binary_op后保存在d_first开始的位置。

从它们的实现也能看出来它们的作用。

示例:

#include <string>#include <ctype.h>#include <algorithm>#include <functional>#include <iostream>int main(){    std::string s("hello");    std::transform(s.begin(), s.end(), s.begin(), ::toupper);    std::cout << s;}

输出是:

HELLO

示例:

    std::string s("hello");    std::string d("kkkkk");    std::transform(s.begin(), s.end(), d.begin(), ::toupper);    std::cout << s << std::endl;    std::cout<<d<<std::endl;

输出是:

helloHELLO

示例:

    std::string s("hello");    std::transform(s.begin(), s.end(), s.begin()+2, ::toupper);    std::cout << s << std::endl;

输出是:

heHEH

最后附上源码

// transformtemplate <class _InputIter, class _OutputIter, class _UnaryOperation>_OutputIter transform(_InputIter __first, _InputIter __last,                      _OutputIter __result, _UnaryOperation __opr) {  __STL_REQUIRES(_InputIter, _InputIterator);  __STL_REQUIRES(_OutputIter, _OutputIterator);  for ( ; __first != __last; ++__first, ++__result)    *__result = __opr(*__first);  return __result;}template <class _InputIter1, class _InputIter2, class _OutputIter,          class _BinaryOperation>_OutputIter transform(_InputIter1 __first1, _InputIter1 __last1,                      _InputIter2 __first2, _OutputIter __result,                      _BinaryOperation __binary_op) {  __STL_REQUIRES(_InputIter1, _InputIterator);  __STL_REQUIRES(_InputIter2, _InputIterator);  __STL_REQUIRES(_OutputIter, _OutputIterator);  for ( ; __first1 != __last1; ++__first1, ++__first2, ++__result)    *__result = __binary_op(*__first1, *__first2);  return __result;}
0 0