1. 程式人生 > >STL算法設計理念 - 函數對象和函數對象當參數和返回值

STL算法設計理念 - 函數對象和函數對象當參數和返回值

實現 dsm last 返回值 class 算法 stream data 結果

函數對象:
重載函數調用操作符的類。其對象常稱為函數對象(function object),即它們是行為類似函數的對象。

一個類對象,表現出一個函數的特征,就是通過“對象名+(參數列表)”的方式使用一個類對象,假設沒有上下文,全然能夠把它看作一個函數對待。
這是通過重載類的operator()來實現的。


“在標準庫中。函數對象被廣泛地使用以獲得彈性”。標準庫中的非常多算法都能夠使用函數對象或者函數來作為自定的回調行為;
demo

#include <iostream>
#include <cstdio>

using namespace std;

// 函數對象。類重載了()
template <typename T>  
class ShowElement
{
public:
	// 重載()
	void operator()(T &t) {
		cout << t << endl;
	}
protected:
private:
	int n;
};

// 函數模版
template <typename T>
void FuncShowElement(T &t)
{
	cout << t << endl;
}

// 普通函數
void FuncShowElement2(int &t)
{
	cout << t << endl;
}

void play01()
{
	int a = 10;
	ShowElement<int> showElement;
	showElement(a); // 函數對象的調用,非常像一個函數,所以叫仿函數
	// 10

	FuncShowElement<int>(a);
	FuncShowElement2(a);
	
}

int main()
{
	play01();
	
	return 0;
}
上面簡單演示了函數對象的使用以及和普通函數定義的異同,看以下的demo。

#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>

using namespace std;

// 函數對象,類重載了()
template <typename T>
class ShowElement
{
public:
	ShowElement() 
	{
		n = 0;
	}
	// 重載()
	void operator()(T &t) {
		++n;
		cout << t << ‘ ‘;
	}

	void printN()
	{
		cout << "n: " << n << endl;
	}
protected:
private:
	int n;
};

// 函數模版
template <typename T>
void FuncShowElement(T &t)
{
	cout << t << ‘ ‘;
}

// 普通函數
void FuncShowElement2(int &t)
{
	cout << t << ‘ ‘;
}

void play01()
{
	int a = 10;
	ShowElement<int> showElement;
	showElement(a); // 函數對象的調用,非常像一個函數,所以叫仿函數
	// 10

	FuncShowElement<int>(a);
	FuncShowElement2(a);

}

// 函數對象的優點
// 函數對象屬於類對象,能突破函數的概念。能保持調用狀態信息
void play02()
{
	vector<int> v;
	v.push_back(1);
	v.push_back(3);
	v.push_back(5);

	for_each(v.begin(), v.end(), ShowElement<int>()); // 匿名函數對象,匿名仿函數
	cout << endl;
	// 1 3 5

	for_each(v.begin(), v.end(), FuncShowElement2); // 通過回調函數
	cout << endl;
	// 1 3 5

	// 改寫一下類ShowElement
	ShowElement<int> showElement;
	/* for_each函數原型

	template<class _InIt,
		class _Fn1> inline
		_Fn1 for_each(_InIt _First, _InIt _Last, _Fn1 _Func)
		{	// perform function for each element
		_DEBUG_RANGE(_First, _Last);
		_DEBUG_POINTER(_Func);
		_For_each(_Unchecked(_First), _Unchecked(_Last), _Func);

		return (_STD move(_Func));
		}
	*/
	// 能夠看出for_each算法的函數對象傳遞是元素值傳遞。不是引用傳遞
	for_each(v.begin(), v.end(), showElement);
	cout << endl;
	showElement.printN(); // 所以這裏打印結果並非我們預期的3
	// n: 0
	
	// 解決方式。for_each最後是把傳進去的函數對象做了值返回
	showElement = for_each(v.begin(), v.end(), showElement);
	cout << endl;
	showElement.printN(); // bingo
	// n: 3
}

int main()
{
	//play01();
	play02();

	return 0;
}
結論:分清楚STL算法返回的值是叠代器還是謂詞(函數對象)是非常重要的。




STL算法設計理念 - 函數對象和函數對象當參數和返回值