arc_lupus
arc_lupus

Reputation: 4116

Getting a part of a QMap as a QVector

I have some elements in a QMap<double, double> a-element. Now I want to get a vector of some values of a. The easiest approach would be (for me):

int length = x1-x0;
QVector<double> retVec;
for(int i = x0; i < length; i++)
{
    retVec.push_back(a.values(i));
}

with x1 and x0 as the stop- and start-positions of the elements to be copied. But is there a faster way instead of using this for-loop?

Edit: With "faster" I mean both faster to type and (not possible, as pointed out) a faster execution. As it has been pointed out, values(i) is not working as expected, thus I will leave it here as pseudo-code until I found a better_working replacement.

Upvotes: 2

Views: 1488

Answers (2)

skypjack
skypjack

Reputation: 50568

Maybe this works:

QVector<double>::fromList(a.values().mid(x0, length));

The idea is to get all the values as a list of doubles, extract the sublist you are interested in, thus create a vector from that list by means of an already existent static method of QVector .

EDIT

As suggested in the comments and in the updated question, it follows a slower to type but faster solution:

QVector<double> v{length};
auto it = a.cbegin()+x0;
for(auto last = it+length; it != last; it++) {
    v.push_back(it.value());
}

I assume that x0 and length take care of the actual length of the key list, so a.cbegin()+x0 is valid and it doesn't worth to add the guard it != a.cend() as well.

Upvotes: 2

dtech
dtech

Reputation: 49329

Try this, shouldn work, haven't tested it:

int length = x1-x0;
QVector<double> retVec;
retVec.reserve(length); // reserve to avoid reallocations
QMap<double, double>::const_iterator i = map.constBegin();
i += x0; // increment to range start
while (length--) retVec << i++.value(); // add value to vector and advance iterator

This assumes the map has actually enough elements, thus the iterator is not tested before use.

Upvotes: 0

Related Questions