Iterators versus. Qt-based index

For this reason, iterators are rarely useful in connection with a QList. One place where STL style iterators make sense has as its arguments a common

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

So, if I have a for loop, where the foreach macro is not 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 } 
+4
source share
4 answers

Qt has its own foreach macro. I also can't think of why foreach is not an option ...

The most important difference is whether you need to change the contents of the list in a loop, as this can be more difficult to read using the index APIs.

If you just want to do something for each of the elements, I have these settings:

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

But this is really a matter of style. If this is so important for performance that you need to worry about minor differences, you should consider redesigning or writing your own custom list.

+3
source

I think it depends on what blah blah blah really does, but usually I would choose the latter form in combination with the std::foreach function, but I think this is just a matter of taste.

By the way, do you mean std::foreach when writing the foreach macro? If so, note that this is not a macro.

+2
source

I would also think about what performance limit might be between the two versions. Constantly computing list [i] is much more expensive than computing ++ I once. If you really want to use index notation and don’t experience too much performance loss, I suggest throwing a link there to hold things.

 for(int i = 0; i < list.size(); ++i) { ListItem &list_item = list[i]; // do something with list_item } 

[I also used ++ i instead of i ++, since it is supposedly faster as a general rule.]

+2
source

In this particular example, there is not much difference.

It is also always useful to learn with stl-type iterators, but they are especially convenient when you start learning stl algorithms like foreach . But do not stop there, of course, go for transform , sort , remove_copy_if and many others.

After all, they are part of the standard library!

+1
source

Source: https://habr.com/ru/post/1338100/


All Articles