1. 程式人生 > 實用技巧 >std::bind1st和std::bind2nd

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