C++ STL算法

STL算法用来处理容器,用模板函数实现。

//STLalgorithm.cpp

#include
#include
#include
using namespace std;

void dump(int i){cout<i2;
}

int main()
{
	vector v(10);
	//随机产生整数加入v
	generate(v.begin(), v.end(), rand);
	//用0替换v中的奇数元素
	replace_if(v.begin(), v.end(), odd, 0);
	//v中降序排序
	sort(v.begin(), v.end(), comp);
	//输出每一个元素
	for_each(v.begin(), v.end(), dump);

	return 0;
}

//STLalgorithm2.cpp

#include
#include

using namespace std;

void print(const char* msg, char a[], int len)
{
	cout<(cout, " "));
}

int main()
{
	const int len=27;
	const int med=len/2;

	char alph[]="abcdefghijklmnopqrstuvwxyz{";
	print("\n\nOriginal array:\n",alph,len);

	random_shuffle(alph, alph+len);
	print("\n\nAfter random shuffle:\n",alph,len);

	nth_element(alph, alph+med, alph+len);
	print("\n\nAfter nth_element:\n",alph,len);
	print("\n\t < median:",alph,med);
	print("\n\t median:",alph + med , 1);
	print("\n\t >median:",alph+med+1,len/2);
	cout<


你可能感兴趣的:(C++)