Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterators v.s. index based for loops in Qt

For that reason, iterators are rarely useful in connection with QList. One place where STL-style iterators do make sense is as arguments to generic

http://doc.qt.digia.com/4.2/qlist-iterator.html

So if I have a for loop, where the macro foreach isn't an option. Should I use iterators or indexes?

  for(int i = 0; i < list.size(); i++) {

       Do something with list[i]

       blah blah blah

  }



  for(QList<type>::iterator i = list.begin(); i != list.end(); ++i) {

          Do something with *i

          blah blah blah

  }
like image 768
user421616 Avatar asked Feb 26 '23 05:02

user421616


1 Answers

Qt has it own foreach macro. I also can´t think of a reason why foreach is not an option...

The most important difference is whether you need to modify the list contents in the loop, as this may get harder to read with index API.

If you just want to do something for each of the items i have those preferences:

  1. Use foreach with a (const-)reference type and let the framework do the right thing
  2. Use index api ::at(int) (Quote from 4.7 docs: "QList is implemented in such a way that direct index-based access is just as fast as using iterators" & "at() can be faster than operator[]"
  3. Use iterator API

But it really is just a question of style. If this is something so critical for performance that you need to worry about the minor differences you should think about redesign or writing your own specialized list.

like image 60
sanosdole Avatar answered Feb 27 '23 17:02

sanosdole