jwm
jwm

Reputation: 5030

QVector<QVector<>> size

I want to know the number of total elements in an object of QVector<QVector<type>>, say myobject. One way to do this is to set a for-loop as follows:

int siz;
QVector<type> temp;
for(int i=0; i<myobject.size(); i++)
{
    temp = myobject[i];
   for(int j=0; j<temp.size(); j++)
   {
     siz += temp.size();
   }
}

Although workable, this way I feel is pretty cumbersome. Is there any more efficient or neater alternatives to estimate the size of QVector<QVector<type>>

Upvotes: 0

Views: 458

Answers (2)

R Sahu
R Sahu

Reputation: 206607

The logic used in your posted code is incorrect.

temp = myobject[i];
for(int j=0; j<temp.size(); j++)
{
  siz += temp.size();
}

adds the size of temp to siz too many times. It needs to added to siz only once.

You need:

int siz = 0;
for(int i=0; i<myobject.size(); i++)
{
   siz += myobject.at(i).size();
}

As pointed out by @Mike, use of myobject[i] may result in a deep copy. For read-only access, use myobject.at(i).

From the documentation:

at() can be faster than operator[](), because it never causes a deep copy to occur.

Upvotes: 2

Mike
Mike

Reputation: 8355

In addition to the answer by R Sahu, I just want to point out that you are incurring a gratuitous copy of the inner QVector object in every iteration of the outer loop. You might want to get a const reference to the inner vector instead.

Another way of doing this would be using std::accumulate algorithm i.e.:

int wholeSize = std::accumulate(m.cbegin(), m.cend(), 0,
                                [](int currentSize, const QVector<type> &v) {
                                  return currentSize + v.size();
                                });

Upvotes: 2

Related Questions