the FOREACH macro
Hi,
I would like to do something like this, which is the WISH case:
typedef map<int, double> hash;
hash a;
// ...
FOREACH(a, key, value, hash)
std::cout << key << "->" << value << "\n";
I already can do something similar, which is the ALREADY-HAVE case:
FOREACH(hash, i, hash)
std::cout << i->first << "->" << i->second << "\n";
with a macro that I defined this way (inspired by the iteration macros
in the Boost Graph Library):
#define FOREACH(MNAME, INAME, MapType) \
for (MapType::iterator \
INAME = MNAME.begin(); INAME != MNAME.end(); ++INAME)
The complete source code for the example above is at the bottom of this
message.
You may rightfully argue that this macro makes little sense, because
you can just have a regular loop there. However, in my real code
(what I gave you here is just a show case) there are two loops and I
want to put then into a macro.
Now, the problem is that I can't declare in the for-loop the variables
key and value as shown in the WISH case. I don't have this problem in
the ALREADY-HAVE case, becasue I only have to declare an iterator.
Thanks for reading. Any ideas how to get closer to my WISH case?
Thanks & best,
Irek
*********************************************
#include <iostream>
#include <map>
#define FOREACH(MNAME, INAME, MapType) \
for (MapType::iterator \
INAME = MNAME.begin(); INAME != MNAME.end(); ++INAME)
using namespace std;
typedef map<int, double> hash;
int main()
{
hash a;
a[0] = 1.71;
a[1] = 3.14;
FOREACH(a, i, hash)
cout << i->first << "->" << i->second << "\n";
return 0;
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]