码迷,mamicode.com
首页 > 其他好文 > 详细

transform使用详解

时间:2015-04-25 15:09:18      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:


文件原型及可能的实现:

版本一:

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;

输出是:

hello
HELLO

示例:

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

输出是:

heHEH

最后附上源码

// transform

template <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;
}

transform使用详解

标签:

原文地址:http://blog.csdn.net/yapian8/article/details/45270179

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!