473,385 Members | 1,486 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

looping through hashmap

Hi,

I'm trying to loop over the elements in a hashmap of the
STL-implementation by SGI. The point is, that because the key/value pair
is stored as std::pair in the COntainer, the code becomes very ugly
and unreadable soon. I'm aware that there exists the for_each-template,
but this doesn't make the code any better because the body of the
for-loop must then live in an extra function (consider two nested
loops). Now I tried to mimic the "for (key in array)"-construct of AWK
using the C++-preprocessor. I've come up with two different versions:

This one requires GNU-extensions (it's used to declare the Iterator in
the initializer-statement of the for loop, and simultaneously setting up
the loop-variables), but has the advantage that in use it looks like an
ordinary for-loop (refer to the sample program below)

#define FOREACH(key, value, hashmap) \
if (!hashmap.empty()) \
for ( { typedef typeof(hashmap) __type##hashmap; \
__type##hashmap::iterator __it##key=hashmap.begin(); \
value=__it##key->second; key=__it##key->first; } \
__it##key!=hashmap.end(); \
(++__it##key!=hashmap.end()) && \
(value=__it##key->second, &(key=__it##key->first)!=NULL) )
This one is (should be) ANSI-C++ compliant, but requires that you
structure the program using FOR..ENDFOR instead of curly braces (since I
need to set the variables inside the body of the for loop). It uses
references for the loop-variables that are automagically declared.

#define FORREF(key, value, hashmap) \
{ typedef typeof(hashmap) __type##hashmap; \
for (__type##hashmap::iterator __it##key=hashmap.begin(); \
__it##key!=hashmap.end(); \
++__it##key!=hashmap.end() ) { \
const __type##hashmap::key_type& key=__it##key->first; \
__type##hashmap::data_type& value=__it##key->second;

#define ENDFOR } }

Are there any pitfalls? I've used the ## tokenpaste operator to create
new variable names in order to avoid that there are identical ones for
nested loops.

Here is the sample application (count identical lines until eof is read)

#include <iostream>
#include <string>
#include <hash_map>
using namespace std;

class zeroint {
// int that initializes as 0
//
int value;
public:
zeroint(int v=0) : value(v) {}
zeroint(const zeroint& z) { value=z.value; }
zeroint& operator = (const zeroint& z) { value=z.value; return
*this; }
zeroint& operator ++ () { ++value; return *this; }
operator const int() const { return value; }
};
struct hash<string>:hash<const char*> {
size_t operator () (const string& x) const {
return this->hash<const char*>::operator () (x.c_str());
}
};

typedef hash_map<string, zeroint, hash<string> > stringmap;
int main() {
string mist;
stringmap wordmap;

//read in the lines
while (mist!="eof") {
cin>>mist;
++wordmap[mist];
}

//output the count using the first version
string word;
zeroint anzahl;
FOREACH(word, anzahl, wordmap) {
cout<<word<<"\t"<<anzahl<<endl;
}

cout<<endl;

// Application of the second version
// increase every mapped number by 10
FORREF(myword, numr, wordmap)
numr=numr+10;
ENDFOR

// output the count using the second version
// static_cast is necessary, because
// there is no operator<< for zeroints
FORREF(wortr, numr, wordmap)
cout<<wortr<<"\t"<<static_cast<const int&>(numr)<<endl;
ENDFOR

return 0;
}
--
Vale !
Christianus Auriocus

Jul 19 '05 #1
1 16767
Christian Gollwitzer wrote:
Hi,

I'm trying to loop over the elements in a hashmap of the
STL-implementation by SGI. The point is, that because the key/value pair
is stored as std::pair in the COntainer, the code becomes very ugly
and unreadable soon. I'm aware that there exists the for_each-template,
but this doesn't make the code any better because the body of the
for-loop must then live in an extra function (consider two nested
loops). Now I tried to mimic the "for (key in array)"-construct of AWK
using the C++-preprocessor. I've come up with two different versions:


This is not such a big deal. For example, here is how I recently did it:

(Pardon the formatting. Map is basically a hash_map of words to list of
occurances by line number.)

typedef hash_map<string,
deque<int>,
hash<string>,
equal_to<string> > Map;

Map wmap;
/*...*/

/* display word and associated line numbers */
for(Map::iterator i=wmap.begin(); i != wmap.end(); ++i){
cout << (*i).first << " ";
copy((*i).second.begin(),
(*i).second.end(),
ostream_iterator<int>(cout, " "));
cout << endl;
}

The tricky part (and perhaps the ugly part) is getting the iterators to
the mapped value (as opposed to the key). You can wrap this in a macro,
function, or whatever you like.

/david

--
"As a scientist, Throckmorton knew that if he were ever to break wind in
the echo chamber, he would never hear the end of it."

Jul 19 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Welson Sun | last post by:
Hi, I am new to UML, I would like to know how can represent JAVA's ArrayList and HashMap with UML diagram? How can I represent the element's class in the ArrayList/HashMap? How is the key in the...
2
by: dougjrs | last post by:
I have a HashMap that is storing form data that will later be inserted into a database. I have been able to create the HashMap just fine, but I wanted to be able to take my HashMap and just "dump"...
1
by: sam | last post by:
Hi, There is a list of items stored in a STL hashmap table. How can I remove a pair of key/value in the hashmap table? Thanks Sam
4
by: David | last post by:
Hi, I have created the following HashMap class. class HashMap: public hash_map<string, string, HashString, HashStringCompare> { public: HashMap(): hash_map<string, string, HashString,...
2
by: xor | last post by:
I'm doing up a school project using java, and am a little new to it (I've worked with other languages for years though). I've seen code posted by the instructor using HashMap like this... ...
6
by: bumrag | last post by:
This is the car dealership object relating to the coursework, there is also a separate object named car that i think i need to link to. The problem is on the addcar() method. Any help would be...
4
by: panos100m | last post by:
Hi these are the conents of my hashmap printing out the entrySet. entrySet1: OrderDate=10/30/2007, entrySet2: Level_0={Item_0={ItemTotal= 3.99, ItemName=test® in, ShipDate=10/31/2007,...
15
by: lbrtchx | last post by:
Hi, ~ I have found myself in need of some code resembling a Hashmap ~ This is easily done in Java this way: ~ import java.util.*; // __ public class JMith00Test{
1
by: evelina | last post by:
Hello, I need help. I have the following hashmap: HashMap<HashMap<Dimension, Integer>, String> mapList = new HashMap<HashMap<Dimension, Integer>, String>(); I want to extract Dimesion from the...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.