001.無參數lambda表達式使用實例

#include<iostream>
#include<vector>
#include<algorithm>
#include<cmath>
#include<ctime>

using namespace std;

//定義全局變量
const long Size1 = 39L;
const long Size2 = 100 * Size1;
const long Size3 = 100 * Size2;

//定義仿函數
bool f3(int x)
{
	return x % 3 == 0;
}

bool f13(int x)
{
	return x % 13 == 0;
}

int main()
{
	vector<int>numbers(Size1);

	srand(time(0));
	generate(numbers.begin(), numbers.end(), rand);//生成隨機數

	//使用函數指針
	cout << "Sample size=" << Size1 << endl;

	int count3 = count_if(numbers.begin(), numbers.end(), f3);
	cout << "Count of numbers divisible by 3:" << count3 << endl;
	int count13 = count_if(numbers.begin(), numbers.end(), f13);
	cout << "Count of numbers divisible by 13:" << count13 << endl;

	//增加numbers中的數字
	numbers.resize(Size2);
	generate(numbers.begin(), numbers.end(), rand);//生成隨機數
	cout << "Sample size=" << Size2 << endl;

	//using a functor
	class f_mod
	{
	private:
		int dv;
	public:
		f_mod(int d = 1) :dv(d) {}//構造函數
		bool operator()(int x)
		{
			return x % dv == 0;
		}
	};

	count3 = count_if(numbers.begin(), numbers.end(), f_mod(3));//注意這裏的特殊寫法
	cout << "Count of numbers divisible by 3:" << count3 << endl;
	count13 = count_if(numbers.begin(), numbers.end(), f_mod(13));//注意這裏的特殊寫法
	cout << "Count of numbers divisible by 13:" << count13 << endl;

	//increase number of numbers again
	numbers.resize(Size3);
	generate(numbers.begin(), numbers.end(), rand);//生成隨機數
	cout << "Sample size=" << Size3 << endl;

	//使用lambda表達式
	count3 = count_if(numbers.begin(), numbers.end(),
		[](int x)
		{
			return x % 3 == 0;
		}
	);
	cout << "Count of numbers divisible by 3:" << count3 << endl;
	count13 = count_if(numbers.begin(), numbers.end(),
		[](int x)
		{
			return x % 13 == 0;
		}
	);
	cout << "Count of numbers divisible by 13:" << count13 << endl;

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