std::for_each with C-style arrays
Although std::for_each is most often used with the standard containers, it can also be used with C-style arrays. Take for example the following:
#include <algorithm>Or if you prefer:
#include <functional>
// ...
WriterTask writer[NumThreads];
std::for_each(writer, writer+NumThreads,
std::mem_fun_ref(&WriterTask::activate));
// ...
std::for_each(writer, writer+NumThreads,
std::mem_fun_ref(&WriterTask::join));
std::for_each(&writer[0], &writer[NumThreads],Compare the above with the explicit for loop:
std::mem_fun_ref(&WriterTask::activate));
for (int i = 0; i < NumThreads; ++i) {
writer[i].activate();
}I'm not completely convinced that the std::for_each case is more readable. However, I liked it better than the for loop for some test cases I was writing. It collapsed a number of subsequent for loops down into one line statements making it clearer the intent of the test.

0 Comments:
Post a Comment
<< Home