It doesn't work because typeof(X)
yields std::vector
type and so the macro expands to something like:
for (vector<std::vector<...> >::iterator it = X.begin(); it != X.end(); it++)
Also, your macro would fail if X
is constant, in which case const_iterator
should be used. There are tons of other problems, but at any rate, what you were trying to do is something like this:
#define VECTOR_LOOP_V(X) \
for (typeof(X.begin()) it = X.begin(), eit = X.end(); it != eit; ++it)
.. and here is some usage example:
#include <vector>
#include <iostream>
#define VECTOR_LOOP_V(X) \
for (typeof(X.begin()) it = X.begin(), eit = X.end(); it != eit; ++it)
int main()
{
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
VECTOR_LOOP_V(v) {
std::cout << *it << std::endl;
}
}
Note, however, that typeof
is not a standard C++ (see this Q/A).
All in all, you are better off using BOOST_FOREACH (or at least see how it is implemented there) or C++11 range-based for loop.
P.S.: Do not use the STL abbreviation unless you really mean STL and not C++ Standard Library (which you can refer to as, say, stdlib).