user421616
user421616

Reputation: 113

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

  }

Upvotes: 4

Views: 4726

Answers (4)

sanosdole
sanosdole

Reputation: 2489

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.

Upvotes: 3

jwernerny
jwernerny

Reputation: 7048

I'd also consider what the performance penalty may be between the two versions. Constantly computing list[i] is much more costly than computing ++i once. If you really want to use index notation and not suffer too much performance loss, I suggest throwing a reference in there to hold things.

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

   ListItem &list_item = list[i];

   // do something with list_item
}

[I'd also use ++i instead of i++ as it is supposedly faster as a general rule.]

Upvotes: 2

xtofl
xtofl

Reputation: 41519

In this specific example, there is no big difference.

Apart from that, it's always a good idea to learn using stl-type iterators, but they come in especially handy when you start learning the stl algorithms, like indeed foreach. But don't stop there - certainly go for transform, sort, remove_copy_if and many more.

After all, they're part of the standard library!

Upvotes: 1

Simone
Simone

Reputation: 11797

I think it depends on what "blah blah blah" really does, but usually I'd choose the latter form in conjunction with std::foreach function, but it's only a matter of taste, I suppose.

By the way, do you mean std::foreach when you write macro foreach? If so, pay attention to the fact that it is not a macro.

Upvotes: 2

Related Questions