std::transform
template< class InputIt, class OutputIt, class UnaryOperation > OutputIt transform( InputIt first1, InputIt last1, OutputIt d_first, UnaryOperation unary_op ); |
(1) | |
template< class InputIt1, class InputIt2, class OutputIt, class BinaryOperation > OutputIt transform( InputIt1 first1, InputIt1 last1, InputIt2 first2, OutputIt d_first, BinaryOperation binary_op ); |
(2) | |
, d_first.
unary_op [first1, last1). binary_op : [first1, last1) first2.
[first1, last1)
|
||
| first2 | ||
| d_first | , first1 first2
| |
| unary_op | unary operation function object that will be applied. The signature of the function should be equivalent to the following:
The signature does not need to have | |
| binary_op | binary operation function object that will be applied. The signature of the function should be equivalent to the following:
The signature does not need to have | |
-InputIt InputIterator.
| ||
-InputIt1 InputIterator.
| ||
-InputIt2 InputIterator.
| ||
-OutputIt OutputIterator.
| ||
Output- , .
1) std::distance(first1, last1) unary_op.
2) std::distance(first1, last1) binary_op.
unary_op binary_op . ( C++11)
unary_op binary_op ( ) . ( C++11)
std::transform. , std::for_each.
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;
}
|
template<class InputIt1, class InputIt2,
class OutputIt, class BinaryOperation>
OutputIt transform(InputIt first1, InputIt last1, InputIt first2,
OutputIt d_first, BinaryOperation binary_op)
{
while (first1 != last1) {
*d_first++ = binary_op(*first1++, *first2++);
}
return d_first;
}
|
std::transform std::toupper:
#include <string>
#include <cctype>
#include <algorithm>
#include <iostream>
int main()
{
std::string s("hello");
std::transform(s.begin(), s.end(), s.begin(), (int (*)(int))std::toupper);
std::cout << s;
}
:
HELLO
.
| ( ) |