///----http://www.josuttis.com/libbook/toc.html
#include <iostream>
#include <vector>#include <set>
#include <algorithm>
template <class T>
inline void PRINT_ELEMENTS (const T& coll, const char* optcstr="")
{
typename T::const_iterator pos;
std::cout << optcstr;
for (pos=coll.begin(); pos!=coll.end(); ++pos) {
std::cout << *pos << ' ';
}
std::cout << std::endl;
}
int square (int value)
{
return value*value;
}
int main()
{
std::set<int> coll1;
std::vector<int> coll2;
// insert elements from 1 to 9 into coll1
for (int i=1; i<=9; ++i) {
coll1.insert(i);
}
PRINT_ELEMENTS(coll1,"initialized: ");
// transform each element from coll1 to coll2
// - square transformed values
std::transform (coll1.begin(),coll1.end(), // source
std::back_inserter(coll2), // destination
square); // operation
PRINT_ELEMENTS(coll2,"squared: ");
}
//------------------foreach
// function that prints the passed argument
void print (int elem)
{
cout << elem << ' ';
}
int main()
{
vector<int> coll;
// insert elements from 1 to 9
for (int i=1; i<=9; ++i) {
coll.push_back(i);
}
// print all elements
for_each (coll.begin(), coll.end(), // range
print); // operation
cout << endl;
}
//---------------------foreach
class PrintInt {
public:
void operator() (int elem) const {
cout << elem << ' ';
}
};
for_each (coll.begin(), coll.end(), PrintInt());
//--------------------find_if
bool isPrime (int number)
{ // ignore negative sign
number = abs(number);
if (number == 0 || number == 1) {// 0 and 1 are no prime numbers
return false;
}
int divisor;// find divisor that divides without a remainder
for (divisor = number/2; number%divisor != 0; --divisor) {; }
return divisor == 1;// if no divisor greater than 1 is found, it is a prime number
}
list<int>::iterator pos;
pos = find_if (coll.begin(), coll.end(), isPrime); // range