《Essential C++》系列笔记之第三章(泛型编程风格)之第五节(使用泛型算法)

《Essential C++》系列笔记之第三章(泛型编程风格)之第五节(使用泛型算法)_第1张图片
代码实践

#include 
using namespace std;
#include 
#include 

void demo_find()
{
	int a[] = { 1,46,2,6,8,4,23,7,9 };
	vector<int> ivec(a, a + sizeof(a) / sizeof(a[0]));
	cout << *find(ivec.begin() + 3, ivec.end(), 23) << endl;
	//cout << *find(ivec.begin(), ivec.end(), 33) << endl; //会返回一个指向last的指针,所以这样有些危险!
}

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

	for (int i = 0; i < 10; i++)
	{
		cout << ivec[i] << ' ';
	}
	cout << endl;

	cout << binary_search(ivec.begin() + 1, ivec.end(), 1) << endl;

}

void demo_count()
{
	int a[] = { 1,46,2,6,8,4,23,23,7,9,23 };
	vector<int> ivec(a, a + sizeof(a) / sizeof(a[0]));

	cout << count(ivec.begin(), ivec.end() - 1, 100) << endl;
}

void demo_max_element()
{
	int a[] = { 123,235,234,345,576,67694,234,456 };
	vector<int> ivec(a, a + sizeof(a) / sizeof(a[0]));
	vector<int> ivec2;
	int max = *max_element(ivec2.begin(), ivec2.end());
	//max_elementf返回是一个iterator啊,与书中有些出入
}

void demo_copy()
{
	int a[] = { 123,235,234,345,576,67694,234,456 };
	vector<int> ivec(a, a + sizeof(a) / sizeof(a[0]));

	vector<int> ivec2(30);   //如果写成vector ivec2; 目标容器没有足够空间放置即将到来的元素,会报错!!!
	copy(ivec.begin(), ivec.begin() + 4, ivec2.begin());

	for (int i = 0; i < ivec2.size(); i++)
	{
		cout << ivec2[i] << ' ';
	}
	cout << endl;

	sort(ivec2.begin(), ivec2.begin() + 4);
	for (int i = 0; i < ivec2.size(); i++)
	{
		cout << ivec2[i] << ' ';
	}
	cout << endl;

}

int main()
{
	//demo_find();

	//demo_binary_search();

	//demo_count();

	//demo_max_element();

	//demo_copy();

	system("pause");
	return 0;
}

今天是20200309 不说了,恰饭!

你可能感兴趣的:(《Essential,C++》系列笔记)