文件原型及可能的实现:
版本一:
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;
}
对first1
、last1
范围内的元素执行一元操作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;
}
对first1
、last1
及first2
二元操作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;
}
原文:http://blog.csdn.net/yapian8/article/details/45270179