The each macro allows you to iterate over any STL-compatible sequence in way known from many other languages.
You can use the for each construction over any container type that exposes .begin() and .end() member functions. Both member functions must return an object of iterator type (but not neccessary a STL iterator), .begin() refering to first enumerated element, .end() refering to element one-pass-end of the enumeration. The for each operates on the same range of elements as std::for_each does.
The each is implemented as a macro defined in "ext/ext_bits/each" file. Include the <ext/c++> header file.
The for each takes three parameters, these are:
Note that the supplied iterator must support at least dereference operation (operator*), prefix increment operation (operator++) to advance to next element and non-equivalence comparison operator (operator!=).
#include <ext/c++>
#include <vector>
#include <map>
std::vector <int> c1;
typedef std::map <int, std::string> map_type;
map_type c2;
int main () {
// ...
for each (std::vector <int>::const_iterator, i, c1)
std::printf ("%d, ", *i);
// ...
for each (map_type::iterator, j, c2)
j->second = "null";
// ...
};
Note that in example above the map_type typedef instead of full type name must be used because preprocessor does not handle template parameter list as single macro parameter. The preprocessor would otherwise complain for too many macro parameters.
To maintain backward compatibility with EXT Library version 1.0 without the need to update your source codes, you can define EXT_UNNAMED_EACH to get the old version of the for each. This one misses the iterator-name parameter, you need to use the "iterator" variable name inside the loop in order to access current element. Also note that the old version of the for each cannot nest.
Because the each is implemented as a macro, you will experience difficulties if you are using the word as a variable name or a type name. To fix these, you will need to either update your codes not to use each in constructs other than for each, or your can define EXT_FAIR_MACROS and use EACH then instead.
If you decided not to use for each, you can disable it by defining EXT_NO_EACH before including <ext/c++>. You can also disable all macros by defining EXT_NO_MACROS.
Tip: You may wish to add the each keyword to your editor highlights.
[index]