c++STL函數對象、謂詞——全面總結(附案例解析)(二十一)

這裏有C++STL——全面總結詳細教程(附案例解析)(持續更新中)


目錄

STL- 函數對象

函數對象

函數對象概念

函數對象使用

謂詞

謂詞概念

一元謂詞

二元謂詞


STL- 函數對象

函數對象

函數對象概念

概念:

  • 重載函數調用操作符的類,其對象常稱爲函數對象

  • 函數對象使用重載的()時,行爲類似函數調用,也叫仿函數

本質:

函數對象(仿函數)是一個,不是一個函數

 

函數對象使用

特點:

  • 函數對象在使用時,可以像普通函數那樣調用, 可以有參數,可以有返回值
  • 函數對象超出普通函數的概念,函數對象可以有自己的狀態
  • 函數對象可以作爲參數傳遞
#include<iostream>
#include<string>
using namespace std;

//1、函數對象在使用時,可以像普通函數那樣調用, 可以有參數,可以有返回值
class MyAdd {
public:
	int operator()(int v1, int v2) {
		return v1 + v2;
	}
};

void test01() {
	MyAdd myAdd;
	cout << myAdd(10, 10) << endl;
}

//2、函數對象可以有自己的狀態
class MyPrint {
public:
	MyPrint() {
		count = 0;
	}
	void operator()(string test) {
		cout << test << endl;
		count++;
	}
	int count;
};

void test02() {
	MyPrint myPrint;
	myPrint("hello world");
	myPrint("hello world");
	myPrint("hello world");
	cout << "myPrint調用次數爲:" << myPrint.count << endl;
}

//3、函數對象可以作爲參數傳遞
void doPrint(MyPrint &mp, string test) {
	mp(test);
}

void test03() {
	MyPrint myPrint;
	doPrint(myPrint, "hello c++");
}


int main() {
	test01();
	test02();
	test03();

	system("pause");
	return 0;
}

總結:

  • 仿函數寫法非常靈活,可以作爲參數進行傳遞。

 

 

 

謂詞

謂詞概念

概念:

  • 返回bool類型的仿函數稱爲謂詞

  • 如果operator()接受一個參數,那麼叫做一元謂詞

  • 如果operator()接受兩個參數,那麼叫做二元謂詞

 

一元謂詞

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;

class GreateFive {
public:
	bool operator()(int val) {
		return val > 5;
	}
};

void test01() {
	vector<int>v;
	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}

	vector<int>::iterator it = find_if(v.begin(), v.end(), GreateFive());
	if (it == v.end()) {
		cout << "沒找到" << endl;
	}
	else {
		cout << "找到:  " << *it << endl;
	}
}


int main() {
	test01();

	system("pause");
	return 0;
}

總結:參數只有一個的謂詞,稱爲一元謂詞

 

 

二元謂詞

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;

class MyCompare {
public:
	bool operator()(int v1,int v2) {
		return v1 > v2;
	}
};

void test01() {
	vector<int>v;
	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}

	sort(v.begin(), v.end(), MyCompare());
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
		cout << *it << "  ";
	}
	cout << endl;

}


int main() {
	test01();

	system("pause");
	return 0;
}

總結:參數只有兩個的謂詞,稱爲二元謂詞

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章