I'm always trying to learn more about the languages I use (different styles, frameworks, patterns, etc). I've noticed that I never use std::for_each
so I thought that perhaps I should start. The goal in such cases is to expand my mind and not to improve the code in some measure (readability, expressiveness, compactness, etc).
So with that context in mind, is a good idea to use std::for_each
for simple tasks like, say, printing out a vector:
for_each(v.begin(), v.end(), [](int n) { cout << n << endl; }
(The [](int n)
being a lambda function). Instead of:
for(int i=0; i<v.size(); i++) { cout << v[i] << endl; }
I hope this question doesn't seem pointless. I guess it almost asks a larger question... should an intermediate programmer use a language feature even though he doesn't really need to at this time but just so that he can understand the feature better for a time that may actually greatly benefit from it. Although this larger question has probably already been asked (e.g. here).
See Question&Answers more detail:os