Monday, March 10, 2008

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>
#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));
Or if you prefer:
std::for_each(&writer[0], &writer[NumThreads],
std::mem_fun_ref(&WriterTask::activate));
Compare the above with the explicit for loop:
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.

2 comments:

Anonymous said...

shouldnt it be:

std::for_each(&writer[0], &writer[NumThreads-1]

Anonymous said...

nvm I was wrong, seems it stops 1 element before InputIterator last