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:<
Using std::for_each in combination with a lambda function (since C++11)
std::vector<int> v(20);
std::for_each( v.begin(), v.end(), [] (int item)
{
std::cout << item;
} );
instead of
for(std::vector<int>::const_iterator it = v.begin(); it != v.end(); ++it)
{
std::cout << *it;
}
makes for better looking loops.
I like this one for looping over each line in a file. From a Andrew Koenig column in Dr. Dobbs.
for (string s; getline(stream,s); ) {
// Process line
}
The following idiom is needed to actually remove the elements removed by remove()
or remove_if()
:
vector<int> v;
...
v.erase(remove(v.begin(), v.end(), 42), v.end());
remove()
and remove_if()
just slide non-removed elements forward and report where the new range ends -- they don't (and can't) delete them because they can work on any arbitrary iterator range, not just a container.
copy(istreambuf_iterator<char>(cin), istreambuf_iterator<char>(),
ostream_iterator<char>(cout));
Another oft used idiom is initializing a container from an array:
#include <map>
using namespace std;
int main() {
typedef std::map<char,int> LUT;
typedef LUT::value_type LUT_item_t;
const LUT_item_t items[] = { LUT_item_t('b',1),
LUT_item_t('a',5)
};
LUT my_map(items, items + sizeof items/sizeof items[0]);
return 0;
}
But if you want pure magic, look into Boost Lambda Library ;) A sample:
vector<int*> vp(10);
sort(vp.begin(), vp.end(), *_1 > *_2);
For your second example use the value type:
#
Copy a map to a vector:
typedef map<T1, T2> MyMap;
MyMap myMap;
vector< MyMap::value_type > myVec(myMap.begin(), myMap.end());
// std::back_inserter usage ( std::inserter for map )
std::copy( source.begin(), source.end(), std::back_inserter( container ) );
-
// mem_fun and bind usage (but boost better)
std::some_algorithm(..., std::mem_fun( func ) );
not so useful, but powerful:
check is container sorted
std::adjacent_find( container.begin(), container.end(), greater<Container::value_type>() ) == container.end()
also examples mentioned by you and dirkgently.