I\'m looking for practical and educational samples of C++ / STL code fitting in few lines. My actual favorites are:
Empty a vector freeing its reserved memory:<
My favorite is copying containers to the output: And copying the input stream into a container.
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
int main()
{
std::vector<int> data;
std::copy(std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
std::back_inserter(data)
);
std::copy(data.begin(),data.end(),
std::ostream_iterator<int>(std::cout,"\n")
);
}
What I like most is to use bind1st/bind2nd/mem_fun in sort of delegates.
// will call a->func(v[i])
for_each(v.begin(), v.end(), bind1st(mem_fun(&A::func), &a));
// will call w[i]->func(72)
for_each(w.begin(), w.end(), bind2nd(mem_fun(&A::func), 72));
Using boost's bind and function are much better, but it is impressive which can be done with just STL.