Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cbegin()/cend() vs constBegin()/constEnd()

Tags:

c++

iterator

qt

qt5

Qt 5.0 introduced the iterator methods cbegin() and cend() in the different container classes like QList or QMap.

But there are also constBegin() and constEnd() methods in those classes.

All those methods are const and return an STL-style const_iterator.

  • Do cbegin()/cend() have the same functionality than constBegin()/constEnd() ? For me it seems so, but nothing is stated in the docs of QList, QMap or the container classes.
  • Is there a scenario where one should use cbegin()/cend() instead of constBegin()/constEnd() or vice-versa?
like image 242
Christophe Weis Avatar asked Sep 03 '15 10:09

Christophe Weis


2 Answers

cbegin() and cend() where introduced for compatibility with Standard Library containers, which all contain such functions since C++11.
Qt just wants to keep it interface similar to the standard library. constBegin() etc. are just older versions (Qt added them before C++11 was released). There is no difference in using them.

I'd use constBegin() and constEnd() as they are more explicit and 'Qt style', but that just my personal preference. cbegin()/cend() might be used by some algorithms implemented for standard containers (hence their existence in Qt - they help reuse some code). Use them if you expect that at some point you would like to reuse your code outside Qt.

like image 185
Hcorg Avatar answered Nov 15 '22 03:11

Hcorg


Qt generally often provides different ways of using things, so that programmers can use the style they are used to use.

Simmilar case is with iterators' type. You can use the standard style used in Standard Library or Java style iterators. It's for user's convenience.

The reason for cbegin and constBegin is simillar. Also if documentation does not state difference, then there is no difference.

As you noticed. constBegin is pure QtStyle and cbegin is STL style.

like image 43
DawidPi Avatar answered Nov 15 '22 03:11

DawidPi