transform用法,plus累加,重载【】多种形式,Lambda表达式的使用

1.transform 用法  

static int op_increase(int i) { return ++i; }
void Solve() {
	vector<int>arr(3);
	for (auto& i : arr)cin >> i;
	for (auto i : arr)cout << i << " ";
	cout << endl;

	transform(arr.begin(), arr.end(), arr.begin(), [](int a) {
		return a * 10;
		});
	for (auto i : arr)cout << i << " ";
	cout << endl;

	transform(arr.begin(), arr.end(), arr.begin(),
		[](int a)->int {return a * 10; });
	for (auto i : arr)cout << i << " ";
	cout << endl;

	for_each(arr.begin(), arr.end(), [](int &a) {a *= 10; });
	for (auto i : arr)cout << i << " ";
	cout << endl;

	vector<int> b;
	b.resize(arr.size());
	transform(arr.begin(), arr.end(), b.begin(),
		op_increase);//对a中每个值经过op_increase给b
	transform(arr.begin(), arr.end(), b.begin(),
		[](int a)->int {return a + 10; });//对a中每个值经过op_increase给b
	transform(arr.begin(), arr.end(),b.begin(), arr.begin(), std::plus<int>());
	//plus 累加
	int sum = accumulate(arr.begin(), arr.end(), 0, plus<int>());
	//accumlate可以缺省plus<int>(),默认的
	cout << sum << endl;

	for (auto i : arr)cout << i << " ";
	cout << endl;
	for (auto i : b)cout << i << " ";
	cout << endl;

}


2.C++ lambda表达式 

 C++11中Lambda表达式的使用

3.remove:

remove_if用法

static int op_increase(int i) { return ++i; }
void Solve() {
	vector<int>arr(3);
	for (auto& i : arr)cin >> i;
	transform(arr.begin(), arr.end(), arr.begin(), [](int a) {
		return a * 10;
		});
	for (auto i : arr)cout << i << " ";
	cout << endl;

	int k = 40;
	//remove(arr.begin(),arr.end(),val)将=val放在最后,没有删除,需要erase
	arr.erase(remove_if(arr.begin(), arr.end(), [k](int n) {return n > k; }),arr.end());
	for (auto i : arr)cout << i << " ";


}

4.函数表达形式:

int add(int a, int b){
    return a+b;
}
auto mod=[](int a, int b){return a%b;};
struct divide{
    int operator()(int m, int n){
        return m/n;
    }
};

	auto func1 = [](int i) { return i + 4; };
	std::cout << "func1: " << func1(6) << '\n';
	function<int(int)> fun1 = func1;//调用形式


	auto mod = [](int a, int b) {return a % b; };
	struct divide {
		int operator()(int m, int n) {
			return m / n;
		}
	};
	//抽象定义,不同类型采用相同的调用方法:
	map<string, function<int(int, int)>> funs =
	{
		{"+", add},
		{"-", std::minus<int>()},//标准库的函数,参数为两个整数,可以参考前一篇博客
		{"/", divide()},//类成员函数
		{"*", [](int i,int j) {return i * j; }},//lambda表达式
		{"%", mod},
	};
	funs["+"](4, 6);
	funs["*"](4 , 2);

5.对于set的自定义函数重载

int k;
struct cmp {
	bool operator()(const int& u, const int& v) const{
		if (abs(u - v) <= k)return false;//false 不需要插入进去,insert失效
		return u < v;
	}
};
set<int, cmp>se;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值