transform

/*
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 <iostream>
#include <algorithm>
#include <vector>
#include <string>
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<int> first;
	vector<int> second;
	vector<int>::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;
	//*/

	system("pause");
	return 0;
}

/*
Output:

second contains: 11 21 31 41 51
first contains: 21 41 61 81 101
HELLO, WORLD!
hello, world!
请按任意键继续. . .
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值