Transformの使い方
3679 ワード
Transformの機能は、[first 1,first 2]の要素を演算し、結果をresultに格納する
unary operation(1)(一元演算)
template OutputIterator transform (InputIterator first1, InputIterator last1, OutputIterator result, UnaryOperation op);
binary operation(2)(二元演算)
template class OutputIterator, class BinaryOperation> OutputIterator transform (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, OutputIterator result, BinaryOperation binary_op);
transformには2つの形式があり、1つは1元オペレータであり、もう1つは2元オペレータである.
一元オペレータの場合は、次のようになります.
template
OutputIterator transform (InputIterator first1, InputIterator last1,
OutputIteratorresult, UnaryOperator op)
{
while (first1 != last1) {
*result = op(*first1); // or: *result=binary_op(*first1,*first2++);
++result; ++first1;
}
return result;
}
二元オペレータの場合、各iteratorの意味:
二元オペレータの場合、関数はfirst 1の要素とfirst 2の要素がop演算を行いresultに格納されることを意味する
例:
#include
#include
#include
#include
// The function object multiplies an element by a Factor
template
class MultValue
{
private:
Type Factor; // The value to multiply by
public:
// Constructor initializes the value to multiply by
MultValue ( const Type& _Val ) : Factor ( _Val ) {
}
// The function call for the element to be multiplied
Type operator ( ) ( Type& elem ) const
{
return elem * Factor;
}
};
int main( )
{
using namespace std;
vector v1, v2 ( 7 ), v3 ( 7 );
vector ::iterator Iter1, Iter2 , Iter3;
// Constructing vector v1
int i;
for ( i = -4 ; i <= 2 ; i++ )
{
v1.push_back( i );
}
cout << "Original vector v1 = ( " ;
for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
cout << *Iter1 << " ";
cout << ")." << endl;
// Modifying the vector v1 in place
transform (v1.begin ( ) , v1.end ( ) , v1.begin ( ) , MultValue ( 2 ) );
cout << "The elements of the vector v1 multiplied by 2 in place gives:"
<< "
v1mod = ( " ;
for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
cout << *Iter1 << " ";
cout << ")." << endl;
// Using transform to multiply each element by a factor of 5
transform ( v1.begin ( ) , v1.end ( ) , v2.begin ( ) , MultValue ( 5 ) );
cout << "Multiplying the elements of the vector v1mod
"
<< "by the factor 5 & copying to v2 gives:
v2 = ( " ;
for ( Iter2 = v2.begin( ) ; Iter2 != v2.end( ) ; Iter2++ )
cout << *Iter2 << " ";
cout << ")." << endl;
// The second version of transform used to multiply the
// elements of the vectors v1mod & v2 pairwise
transform ( v1.begin ( ) , v1.end ( ) , v2.begin ( ) , v3.begin ( ) ,
multiplies ( ) );
cout << "Multiplying elements of the vectors v1mod and v2 pairwise "
<< "gives:
v3 = ( " ;
for ( Iter3 = v3.begin( ) ; Iter3 != v3.end( ) ; Iter3++ )
cout << *Iter3 << " ";
cout << ")." << endl;
}