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是否定返回值是双目的函数。

原文地址:https://www.cnblogs.com/zhoug2020/p/13583298.html