1

I have QHash<QString, QHash<quint64, QElapsedTimer*> myNestedQHash; and when I try

foreach (QHash<quint64, QElapsedTimer*>  stat, myNestedQHash.values(someStr))

I get

error: macro "Q_FOREACH" passed 3 arguments, but takes just 2

Isn't it possible to loop on nested QHash they way I did?

mrz
  • 1,802
  • 2
  • 21
  • 32
  • This is a problem with the QHash type definition for stat. try setting this in brackets, i remember having the same problem but i just do not recall ho i solved this. – Sebastian Lange Jul 08 '13 at 10:11
  • if I `typedef QHash statType` then it should work, but I was wondering why this doesn't work... – mrz Jul 08 '13 at 10:27

3 Answers3

3

why not using

for (QHash<QString, QHash<quint64, QElapsedTimer*>::iterator it = myNestedQHash.begin(); it != myNestedQHash.end(); ++it) 
{...}

instead? i think Q_FOREACH will create a copy, so it will be better performance as well...

/edit:

the foreach is just a definition for the Q_FOREACH macro ... so the compiler sees it and it will accept 2 values. since you have a additional comma in it, it will see 3 arguments. you will find all infos here.

mrz
  • 1,802
  • 2
  • 21
  • 32
Zaiborg
  • 2,492
  • 19
  • 28
  • you're right, and I did the same to loop through my nested QHash, but I wanted to know why can't I use foreach, I mean what is the problem there, rather than how to loop on a nested QHash. – mrz Jul 09 '13 at 05:24
  • 1
    the `foreach` is just a definition for the `Q_FOREACH` macro ... so the compiler sees it and it will accept 2 values. since you have a additional comma in it, it will see 3 arguments. you will find all infos here: http://marcmutz.wordpress.com/effective-qt/containers/ ;) – Zaiborg Jul 09 '13 at 06:33
  • cheers, put your comment as an edit in your answer and I will accept it. – mrz Jul 09 '13 at 11:27
  • Qt container copies are lightweight, copy-on-write objects so there's negligible performance impact. – Macke Apr 04 '14 at 08:14
0

Should be working like this:

QHash<QString, int> myHash0;
myHash0["test0"]=0;
myHash0["test1"]=1;
QHash<QString, int> myHash1;
myHash1["test0"]=0;
myHash1["test1"]=1;

QHash<QString, QHash<QString, int> > myHashList;
myHashList["Hash0"] = myHash0;
myHashList["Hash1"] = myHash1;

QHash<QString, int> h;
foreach(h , myHashList)
{
    qDebug()<<h["test0"];
}
Sebastian Lange
  • 3,879
  • 1
  • 19
  • 38
  • I kinda used QString/int now... lazy typer :) But it should work as soon as you take away the ``QHash stat`` away from the foreach macro – Sebastian Lange Jul 08 '13 at 10:52
0

QT foreach is a macro. And parameters in a macro are separated by comma ,

In your case, you use a template with comma inside.

You can write it as:

QHash<quint64, QElapsedTimer*>  stat;  
foreach (stat, myNestedQHash.values(someStr))
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116