1. 程式人生 > >C++STL 預定義函數對象和函數適配器

C++STL 預定義函數對象和函數適配器

取反 基本 操作 參數 res 個數 prot lib http

預定義函數對象和函數適配器

預定義函數對象基本概念:標準模板庫STL提前定義了很多預定義函數對象,#include <functional> 必須包含

1使用預定義函數對象:

void main()
{
	plus<int> intAdd;
	int x = 10;
	int y = 20;
	int z = intAdd(x, y); //等價於 x + y 
	cout << z << endl;

	plus<string> stringAdd;
	string myc = stringAdd("aaa", "bbb");
	cout << myc << endl;

	vector<string> v1;
	v1.push_back("bbb");
	v1.push_back("aaa");
	v1.push_back("ccc");
	v1.push_back("zzzz");
}

  

算術函數對象

預定義的函數對象支持加、減、乘、除、求余和取反。調用的操作符是與type相關聯的實例

加法:plus<Types>

plus<string> stringAdd;

sres = stringAdd(sva1,sva2);

減法:minus<Types>

乘法:multiplies<Types>

除法divides<Tpye>

求余:modulus<Tpye>

取反:negate<Type>

negate<int> intNegate;

ires = intNegate(ires);

Ires= UnaryFunc(negate<int>(),Ival1);

關系函數對象

等於equal_to<Tpye>

equal_to<string> stringEqual;

sres = stringEqual(sval1,sval2);

不等於not_equal_to<Type>

大於 greater<Type>

大於等於greater_equal<Type>

小於 less<Type>

小於等於less_equal<Type>

void main()
{
	vector<string> v1;
	v1.push_back("bbb");
	v1.push_back("aaa");
	v1.push_back("ccc");
	v1.push_back("zzzz");
	v1.push_back("ccc");
	string s1 = "ccc";
	//int num = count_if(v1.begin(),v1.end(), equal_to<string>(),s1);
	int num = count_if(v1.begin(),v1.end(),bind2nd(equal_to<string>(), s1));//bind2nd函數適配器
	cout << num << endl;
} 

  

邏輯函數對象

邏輯與 logical_and<Type>

logical_and<int> indAnd;

ires = intAnd(ival1,ival2);

dres=BinaryFunc( logical_and<double>(),dval1,dval2);

邏輯或logical_or<Type>

邏輯非logical_not<Type>

logical_not<int> IntNot;

Ires = IntNot(ival1);

Dres=UnaryFunc( logical_not<double>,dval1);

函數適配器

技術分享圖片

技術分享圖片

技術分享圖片

技術分享圖片

常用函數函數適配器

1綁定器(binder: binder通過把二元函數對象的一個實參綁定到一個特殊的值上,將其轉換成一元函數對象。C++標準庫提供兩種預定義的binder適配器:bind1stbind2nd,前者把值綁定到二元函數對象的第一個實參上,後者綁定在第二個實參上。

2取反器(negator) : negator是一個將函數對象的值翻轉的函數適配器。標準庫提供兩個預定義的ngeator適配器:not1翻轉一元預定義函數對象的真值,not2翻轉二元謂詞函數的真值。

常用函數適配器列表如下:

bind1st(op, value)

bind2nd(op, value)

not1(op)

not2(op)

class IsGreat
{
public:
	IsGreat(int i)
	{
		m_num = i;
	}
	bool operator()(int &num)
	{
		if (num > m_num)
		{
			return true;
		}
		return false;
	}
protected:
private:
	int m_num;
};

void main()
{
	vector<int>  v1;
	for (int i=0; i<5; i++)
	{
		v1.push_back(i+1);
	}

	for (vector<int>::iterator it = v1.begin(); it!=v1.end(); it ++)
	{
		cout << *it << " " ;
	}

	int num1 = count(v1.begin(), v1.end(), 3);
	cout << "num1:" << num1 << endl;

	//通過謂詞求大於2的個數
	int num2 = count_if(v1.begin(), v1.end(), IsGreat(2)); 
	cout << "num2:" << num2 << endl;

	//通過預定義函數對象求大於2的個數   greater<int>() 有2個參數 
	//												param > 2
	int num3 = count_if(v1.begin(), v1.end(), bind2nd(greater<int>(), 2 ) );
	cout << "num3:" << num3 << endl;

	//取模 能被2整除的數 求奇數
	int num4 = count_if(v1.begin(), v1.end(), bind2nd(modulus <int>(), 2 ) ); 
	cout << "奇數num4:" << num4 << endl;

	int num5 = count_if(v1.begin(), v1.end(), not1( bind2nd(modulus <int>(), 2 ) ) ); 
	cout << "偶數num5:" << num5 << endl;
	return ;
}

  

C++STL 預定義函數對象和函數適配器