3

What is the reason for having methods such as void QList::push_back ( const T & value )

in QT when it is doing the same thing as append() What kind of compatibly does the documentation means. Can any one please elaborate this

Following is the statement from official documentation of QT

"This function is provided for STL compatibility. It is equivalent to append(value)"

Sanyam Goel
  • 2,138
  • 22
  • 40

4 Answers4

7

This is typically used so that method templates that expect standard containers as their template parameters can be used with a QList as well, since they will share the same methods.

For example:

template<typename Container>
void move_elements(Container &to, const std::vector<int> &from)
{
  for (auto elem : from)
    to.push_back(elem);
}

Could be called with both a std::list<int> and a QList<int> as the to parameter.

Nbr44
  • 2,042
  • 13
  • 15
4

it is for compatibility, so you can send QList to algorithms operating on standard containers. I think this is main benefit, so you can use all operations from <algorithm>. I give an example of find_if from <algorithm>:

bool hasChildChecked(){
      return std::find_if(childItems_.begin(), 
                          childItems_.end(),checked()) != childItems_.end();
      }

where my childItems_ is declared as:

QList<TreeItem*> childItems_;

struct checked {
           bool operator()(const TreeItem* t) {
               return t->moduleInfo_.currentlyEnabled;
           }
       };

this kind of compatibility really saves my time and makes coding much easier.

4pie0
  • 29,204
  • 9
  • 82
  • 118
1

You may run into this case:

template <
    template <
        typename ValueType,
        typename Allocator
    > class Container
> class garbage_collector
{
    /* some implementation */
};

Because QList has the same method names as the STL container, it could be used in this context.

nikolas
  • 8,707
  • 9
  • 50
  • 70
0

STL (Standard Template Library) of C++ uses the function push_back() for lists and vectors and thus it is a familiar method for most of the C++ programmers. Thus, they have provided an extra method for template parameter compatibility while calling the method.

user221458
  • 716
  • 2
  • 7
  • 17