一 定义
std::transform 应用给定的函数到范围并存储结果于另一范围。定义于< algorithm >
template < class InputIt , class OutputIt , class UnaryOperation >
OutputIt transform ( InputIt first1, InputIt last1, OutputIt d_first,
UnaryOperation unary_op ) ; ( 1 ) ( C++ 20 前)
template < class InputIt , class OutputIt , class UnaryOperation >
constexpr OutputIt transform ( InputIt first1, InputIt last1, OutputIt d_first,
UnaryOperation unary_op ) ; ( 1 ) ( C++ 20 起)
template < class ExecutionPolicy , class ForwardIt1 , class ForwardIt2 , class UnaryOperation >
ForwardIt2 transform ( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1,
ForwardIt2 d_first, UnaryOperation unary_op ) ; ( 2 ) ( C++ 17 起)
template < class InputIt1 , class InputIt2 , class OutputIt , class BinaryOperation >
OutputIt transform ( InputIt1 first1, InputIt1 last1, InputIt2 first2,
OutputIt d_first, BinaryOperation binary_op ) ; ( 3 ) ( C++ 20 前)
template < class InputIt1 , class InputIt2 , class OutputIt , class BinaryOperation >
constexpr OutputIt transform ( InputIt1 first1, InputIt1 last1, InputIt2 first2,
OutputIt d_first, BinaryOperation binary_op ) ; ( 3 ) ( C++ 20 起)
template < class ExecutionPolicy , class ForwardIt1 , class ForwardIt2 , class ForwardIt3 , class BinaryOperation >
ForwardIt3 transform ( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1,
ForwardIt2 first2, ForwardIt3 d_first, BinaryOperation binary_op ) ; ( 4 ) ( C++ 17 起)
二 Demo
int plus1 ( int a) {
return a + 10 ;
}
int plus2 ( int a, int b) {
return a + b;
}
if ( 1 ) {
std:: list< int > l ( 10 ) ;
std:: vector< int > vc;
fill ( vc, 1 , 9 ) ;
print ( "before transform vc(src): " , vc) ;
print ( "before transform list(dst): " , l) ;
std:: transform ( vc. begin ( ) , vc. end ( ) , l. begin ( ) , plus1) ;
print ( "after transform vc(src): " , vc) ;
print ( "after transform list(dst): " , l) ;
}
if ( 1 ) {
std:: list< int > l ( 10 ) ;
std:: vector< int > vc1;
fill ( vc1, 1 , 9 ) ;
std:: vector< int > vc2;
fill ( vc2, 1 , 9 ) ;
print ( "before transform vc1(src): " , vc1) ;
print ( "before transform vc2(src): " , vc2) ;
print ( "before transform list(dst): " , l) ;
std:: transform ( vc1. begin ( ) , vc1. end ( ) , vc2. begin ( ) , l. begin ( ) , plus2) ;
print ( "after transform vc1(src): " , vc1) ;
print ( "after transform vc2(src): " , vc2) ;
print ( "after transform list(dst): " , l) ;
}
before transform vc ( src) : 1 2 3 4 5 6 7 8 9
before transform list ( dst) : 0 0 0 0 0 0 0 0 0 0
after transform vc ( src) : 1 2 3 4 5 6 7 8 9
after transform list ( dst) : 11 12 13 14 15 16 17 18 19 0
before transform vc1 ( src) : 1 2 3 4 5 6 7 8 9
before transform vc2 ( src) : 1 2 3 4 5 6 7 8 9
before transform list ( dst) : 0 0 0 0 0 0 0 0 0 0
after transform vc1 ( src) : 1 2 3 4 5 6 7 8 9
after transform vc2 ( src) : 1 2 3 4 5 6 7 8 9
after transform list ( dst) : 2 4 6 8 10 12 14 16 18 0
三 参考