//stl/foreach1.cpp
/**//*
函数作为算法的参数
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void print(int elem)
...{
cout <<elem<<' ';
}
int main()
...{
vector<int> coll;
for(int i = 1; i<=9; ++i)
...{
coll.push_back(i);
}
// print 函数作为算法的参数
for_each(coll.begin(),coll.end(),print);
// 这里 for_each函数对 begin - end 区间内的每个元素调用print 函数。
cout <<endl;
}
// Output Result
/**//*
1 2 3 4 5 6 7 8 9
*/
//stl/print.h
#include <iostream>

/**//*
** PRINT_ELEMENTS()
** print all element int zhe collection coll followed by a C_Style String
*/
template <class T>
inline void PRINT_ELEMENTS(const T& coll,const char* optcstr = " ")
...{
typename T::const_iterator pos;
cout << optcstr;
for(pos = coll.begin();pos!= coll.end();++pos)
...{
cout <<*pos << ' ';
}
cout <<endl;
}
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
#include "print.h"
using namespace std;

int squre(int value)
...{
return value*value;
}
int main()
...{
set<int> coll_set;
vector<int> coll_vect;
for(int i =1; i<=9;++i)
...{
coll_set.insert(i);
}
// print
PRINT_ELEMENTS(coll_set,"initialized: ");
transform(coll_set.begin(),coll_set.end(),back_inserter(coll_vect),squre);
//print
PRINT_ELEMENTS(coll_vect,"squared: ");
}
//Output Result
/**//*
initialized: 1 2 3 4 5 6 7 8 9
squared: 1 4 9 16 25 36 49 64 81
*/
判断式的例子
//stl/prime1.cpp
// predicates(判断式),就是返回boolean 值得函数,通常用来指定排序准则,或者搜寻准则。
// 一元判断式及二元判断式,二元的例子以后再写啦
//
// Unary Predicates(一元判断式)
//
#include <iostream>
#include <list>
#include <algorithm>
#include <cstdlib> // using function abs()
using namespace std;
// 判断某个数是不是质数
bool isPrime(int number)
...{
number = abs(number);
if(number ==0||number ==1)
return true;
int divisor;
for(divisor = number/2; number%divisor !=0;--divisor);
return divisor ==1;
}
int main()
...{
list<int> coll;
for(int i =24; i<=30;++i)
...{
coll.push_back(i);
}
list<int>::iterator pos;
// find_if algorithm
pos = find_if(coll.begin(),coll.end(),isPrime);
if(pos != coll.end())
cout <<*pos << " is first prime number found" <<endl;
else
cout <<"no prime number found"<<endl;
}
// Output 
/**//*
** 29 is first prime number found
*/
本文介绍了C++标准模板库(STL)中的算法与容器使用方法,包括如何使用for_each算法配合自定义函数进行集合打印,以及transform算法结合lambda表达式实现数据转换。此外,还探讨了一元判断式在搜索特定元素时的应用。
631

被折叠的 条评论
为什么被折叠?



