# C++ STL算法

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

//STLalgorithm.cpp

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

void dump(int i){cout<<i<<endl;}
bool odd(int i){return i%2!=0;}

bool comp(const int& i1, const int& i2){
return i1>i2;
}

int main()
{
vector<int> 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<algorithm>
#include<iostream>

using namespace std;

void print(const char* msg, char a[], int len)
{
cout<<msg;
copy(a, a+len, ostream_iterator<char>(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<<endl;

return 0;
}