Linked by Eugenia Loli-Queru on Mon 1st Aug 2005 00:05 UTC
Thread beginning with comment 12009
To read all comments associated with this story, please click here.
To read all comments associated with this story, please click here.
RE: Simpler, more efficient approach
by falemagn on Mon 1st Aug 2005 09:51
in reply to "Simpler, more efficient approach"
It's actually possible to make that macro work also with arrays (notice, not pointers), by means of a wrapper around the iterator, and template specialization. So that would cover all common usages of for_each.
If you wanted, though, you could use a macro with 3 arguments, one for the iterator variable name, and two for the begin and end iterators, which would then be able to also use standard pointers. This would be totally equivalent to for_each, except you could use it as a standard for(), in a totally polymorphic way.
RE[2]: Simpler, more efficient approach
by falemagn on Mon 1st Aug 2005 10:55
in reply to "RE: Simpler, more efficient approach"
here's an implementation of foreach, via macro, which also works on arrays: http://phpfi.com/72243





Member since:
2005-07-06
for_each is nice, but there's something even nicer that is possible to implement with compilers that support the typeof() keyword, and with all the compilers that will support the forthcoming "auto" keyword usage.
#define foreach(iter, container)
for (typeof(container.begin()) iter=(container).begin(); iter != (container).end(); ++iter)
#include <vector>
#include <iostream>
int main()
{
std::vector<int> foo;
/* fill in foo */
foreach(iter, foo)
{
std::cout << *iter << std::endl;
}
return 0;
}
However, this does have the shortcoming that it doesn't work with pointers as iterators, but for most usages I think it's actually a better approach.