Question

i want to access a QMap by it's value, but i don't want to iterate over it and find element with same value and use it's key, is there anyway to find QMap key by it's content? my code is :

    QMap<int, QVector<QString> >::iterator it;
QMap <QString, int> m_all_data;

i want to access to element of m_all_data with value of my iterator key;

Was it helpful?

Solution

You can use:

const Key QMap::key ( const T & value ) const 

which returns the first key with value value or

QList<Key> QMap::keys ( const T & value ) const

which returns a list containing all the keys in the map in ascending order.

But it is slow (linear time), because QMap's internal data structure is optimized for fast lookup by key, not by value.

OTHER TIPS

You can use QMap::values (http://qt-project.org/doc/qt-4.8/qmap.html#values) to get the values.

This will give you a QList on which you can iterate through, and for the given value you can get the key using QMap::key (http://qt-project.org/doc/qt-4.8/qmap.html#key) to get the key for the given value.

You could maintain a second QMap with iterators pointing into the first map, i.e.

QMap<QString, int> m_all_data;
QMap<int, QList<QMap<QString, int>::iterator> > m_data_by_int;

Note that each int value would map to list of iterators since there may be multiple map entries with the same value. Using iterators avoids that you duplicate the QString data. You'd have to make sure to keep the two maps syncronized though, so it might be best to wrap the two maps into a 'bidirectional map' class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top