C++ transfrom的使用

1 篇文章 0 订阅

1 定义:

 假设你已知,  自补


2 用法

下面代码简要说明了2种使用方法: 

a. 将容器的元素当做入参

b. 用容器的元素调用其成员函数


3 代码实现

#include <iostream>
#include <string>
#include <vector>

#include <algorithm>  //!< for transfrom function
#include <functional>  //!< for mem_fun function

using namespace std;

//! 自定义函数, 测试用之
string* Add1(string *str)
{
	*str += '1';
	return str;
}

int main()
{
	vector<string*> vctStr;
	vctStr.push_back(new string("hello"));
	vctStr.push_back(new string("boy"));
	vctStr.push_back(new string("girl"));

	for (auto i : vctStr)
	{
		cout << *i << " ";
	}
	cout << endl;

	//! 用法1: 将元素作为参数传入函数
	vector<string*> vctStrDst(vctStr.size());
	transform(vctStr.begin(), vctStr.end(), vctStrDst.begin(), Add1);

	for (auto i : vctStrDst)
	{
		cout << *i << " ";
	}
	cout << endl;

	//! 用法2: 调用元素的成员函数
	vector<int> vctIntDst(vctStr.size());
	transform(vctStr.begin(), vctStr.end(),
		vctIntDst.begin(), mem_fun(&string::size));

	for (auto i : vctIntDst)
	{
		cout << i << " ";
	}
	cout << endl;

	//! 收尾
	for (auto i : vctStr)
	{
		delete i;
	}
	vctStr.clear();

	cin.get();
	return 0;
}


4 运行结果

hello boy girl 
hello1 boy1 girl1 
6 4 5 



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值