c++STL綁定器bind1st和bind2nd

  • 一元函數對象:對象重載了operator(),並且只含有一個形參變量;

  • 二元函數對象:對象重載了operator(),含有兩個形參變量;
    如:

template<class _Ty = void>
	struct greater
		: public binary_function<_Ty, _Ty, bool>
	{	// functor for operator>
	bool operator()(const _Ty& _Left, const _Ty& _Right) const
		{	// apply operator> to operands
		return (_Left > _Right);
		}
	};

使用時:(當然我們一般不會直接這樣用)

greater<int> gt;
gt(Left,Right);   //看起來更像是一個函數調用,所有叫函數對象
  • 以此類推 …

bind1st和bind2nd簡介:

在C++11前,STL中提供了兩個綁定器,bind1st和bind2nd,分別用來綁定二元函數對象的第一個參數和第二個參數。也就是說就是主要針對二元函數對象設計的,用來綁定參數,可以將二元函數轉換成一個一元函數

  1. 當二元函數中兩個參數的第一個參數是一個確定的值時,我們可以使用bind1st;
  2. 當二元函數中兩個參數的第一個參數是二個確定的值時,我們可以使用bind12nd.

使用實例:

#include <iostream>
#include <vector>
#include <algorithm> //所有泛型算法
#include <functional>//所有函數對象
#include <ctime>

template <typename container>
void print_container(container& con){
	typename container::iterator it = con.begin();
	for (; it != con.end(); ++it){
		std::cout << *it << "  ";
	}
	std::cout << std::endl;
}

int main(){
	std::vector<int> vec;
	srand(time(nullptr));//以系統時間爲隨機數種子
	for (int i = 0; i < 20; ++i){
		vec.push_back(rand() % 100 + 1);
	}
	print_container(vec);
	std::sort(vec.begin(), vec.end()); //sort 默認是小到大排序
	print_container(vec);
	std::sort(vec.begin(),vec.end(),std::greater<int>());//從大到小,left>right
	print_container(vec);
	//std::sort(vec.begin(), vec.end(), std::less<int>());//從小到大,left<right
	//print_container(vec);
	//find_if每次從區間[behin(),end())中取一個值,然後和80作比較,但是less和greater都是二元函數對象,需要兩個參數
	//並且我們的一個參數值每次確定爲80
	//bind1st + greater bool opeartor()(80,const _Ty& _Right )綁定const _Ty& _Left  設置爲確定的值
	//bind2nd + less bool opeartor()(const _Ty& _Left,80)綁定const _Ty& _Right  設置爲確定的值
	auto it = std::find_if(vec.begin(),vec.end(),std::bind1st(std::greater<int>(),80));
	//auto it = std::find_if(vec.begin(), vec.end(), std::bind2nd(std::less<int>(), 80));
	if (it != vec.end()){
		vec.insert(it,80);
	}
	print_container(vec);
	/*
	bind 綁定器 + 二元函數對象 = 一元函數對象
	*/
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章