How to return the keys of a map in a vector
Hi,
my method has the following code:
Code:
const QVector<unsigned int> CLandTypes::getLandTypes()
{
QVector<unsigned int> returnValue;
for(QMap<unsigned int, CLandType>::iterator mapLandTypeIterator = (QMap<unsigned int, CLandType>::iterator)d->LandTypes.begin(); mapLandTypeIterator != (QMap<unsigned int, CLandType>::iterator)d->LandTypes.end();++mapLandTypeIterator)
{
returnValue.push_back(mapLandTypeIterator.key());
}
return returnValue;
}
How can it be done in a better way?
Rumo
Re: How to return the keys of a map in a vector
If you really need to have a QVector, then try this:
Code:
const QVector<unsigned int> CLandTypes::getLandTypes()
{
return d->LandTypes.keys().toVector();
}
But according to Qt docs:
Quote:
For most purposes, QList is the right class to use. Its index-based API is more convenient than QLinkedList's iterator-based API, and it is usually faster than QVector because of the way it stores its items in memory. It also expands to less code in your executable.
Re: How to return the keys of a map in a vector
Just as a side node: With toVector() you won't save so much, because it also expands to a loop. It's only a little bit more sophisticated:
Code:
Q_OUTOFLINE_TEMPLATE QVector<T> QList<T>::toVector() const
{
QVector<T> result(size());
for (int i = 0; i < size(); ++i)
result[i] = at(i);
return result;
}
Re: How to return the keys of a map in a vector
Quote:
With toVector() you won't save so much
That's right, it's just to have simpler code, better would be not to use any conversion at all.