Linked by Eugenia Loli-Queru on Mon 1st Aug 2005 00:05 UTC
General Development Don't be jealous of programmers using new languages, such as Python or C#! C++ gives you many ways to iterate through data you've stored in containers, supports for-each, and has helpful devices called lambda functions. Jeff Cogswell shows you how you can fly through your containers with ease.
Thread beginning with comment 12009
To read all comments associated with this story, please click here.
Simpler, more efficient approach
by falemagn on Mon 1st Aug 2005 08:19 UTC
falemagn
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.

falemagn Member since:
2005-07-06

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.

Reply Parent Bookmark Score: 1

falemagn Member since:
2005-07-06

here's an implementation of foreach, via macro, which also works on arrays: http://phpfi.com/72243

Reply Parent Bookmark Score: 1