c++transformの使い方

2443 ワード

/*
template < class InputIterator, class OutputIterator, class UnaryOperator >
  OutputIterator transform ( InputIterator first1,	//         
							InputIterator last1,	//         
							OutputIterator result,	//          
							UnaryOperator op );		//     
// typedef          (*UnaryOperator)(       );

template < class InputIterator1, class InputIterator2,
           class OutputIterator, class BinaryOperator >
  OutputIterator transform ( InputIterator1 first1,		//    1     
							InputIterator1 last1,		//    1     
							InputIterator2 first2,		//    2     ,     1  
							OutputIterator result,		//          ,     1  
                            BinaryOperator binary_op );	//     
// typedef          (*BinaryOperator)(   1    ,   2    );
//*

#include 
#include 
#include 
#include 
using namespace std;

int op_increase (int i)
{
	return i+1; 
}

int op_sum (int i, int j) 
{
	return i+j; 
}

int to_upper(int c)
{
	if (islower(c))
	{ 
		return (c-32); 
	}

	return c;
}

int to_lower(int c)
{
	if (isupper(c))
	{
		return c+32;
	}

	return c;
}

int main () {
	vector first;
	vector second;
	vector::iterator it;
	
	// set some values:
	for (int i=1; i<6; i++) first.push_back (i*10); //  first: 10 20 30 40 50
	
	/// first      1   second  
	second.resize(first.size());		// allocate space !!!           first  
	transform (first.begin(), first.end(), second.begin(), op_increase); // second: 11 21 31 41 51
	cout << "second contains:";
	for (it=second.begin(); it!=second.end(); ++it)
	{
		cout << " " << *it;
	}
	cout << endl;
	//*
	
	/// first      second       ,            first
	transform (first.begin(), first.end(), second.begin(), first.begin(), op_sum); //  first: 21 41 61 81 101
	cout << "first contains:";
	for (it=first.begin(); it!=first.end(); ++it)
		cout << " " << *it;
	cout << endl;
	//*//

	///     /
	string strsrc("Hello, World!");
	string strdest;
	strdest.resize(strsrc.size());		// !!!           strsrc  
	transform(strsrc.begin(), strsrc.end(), strdest.begin(), to_upper);	//      
	cout << strdest << endl;

	transform(strsrc.begin(), strsrc.end(), strdest.begin(), to_lower); //      
	cout << strdest << endl;
	//*/

	return 0;
}