随笔 - 741  文章 - 0  评论 - 260  阅读 - 416万

std::bind1st和std::bind2nd

头文件:fuctional

std::bind1st和std::bind2nd函数用于将一个二元算子转换成一元算子。

bind的意思是“绑定”,1st代表first,2nd代表second,它们的声明如下:

//std::bind1st
template <class Operation, class T>
binder1st<Operation> bind1st (const Operation& op, const T& x);
  
//std::bind2nd
template <class Operation, class T>
binder2nd<Operation> bind2nd (const Operation& op, const T& x);

bind1st相当于作这样的操作:x op value;
bind2nd相当于作这样的操作:value op x;

演示程序:

#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>

const int Len = 10;

int main()
{
	int num[Len] = { 1, 2, 30, 50, 100, 200,  300, 400, 217, 120 };
	std::vector<int> arr(num, num + Len);
	
	//移除所有小于100的元素, 相当于arr.value < 100
	arr.erase(std::remove_if(arr.begin(), arr.end(),
		std::bind2nd(std::less<int>(), 100)), arr.end());
	for (auto elem : arr)
	{
		std::cout << elem << " ";  //input: 100 200 300 400 217 120
	}
	std::cout << std::endl;

	//移除所有大于300的元素, 相当于300 < arr.value
	arr.erase(std::remove_if(arr.begin(), arr.end(),
		std::bind1st(std::less<int>(), 300)), arr.end());
	for (auto elem : arr)
	{
		std::cout << elem << " ";  //input: 100 200 300 217 120
	}
	std::cout << std::endl;

	//移除所有大于200的元素, 相当于arr.value > 200
	arr.erase(std::remove_if(arr.begin(), arr.end(),
		std::bind2nd(std::greater<int>(), 100)), arr.end());
	for (auto elem : arr)
	{
		std::cout << elem << " ";  //input: 100
	}
	std::cout << std::endl;

	//移除所有小于等于100的元素, !(x > k) == (x <= k)
	arr.erase(std::remove_if(arr.begin(), arr.end(),
		std::not1(std::bind2nd(std::greater<int>(), 100))), arr.end());
	for (auto elem : arr)
	{
		std::cout << elem << std::endl;  //input:
	}

	return 0;
}

not1是否定返回值单目的函数,还有一个not2是否定返回值是双目的函数。

posted on   莫水千流  阅读(407)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
历史上的今天:
2014-08-29 关于typedef的用法总结(zz)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示