Reputation: 369
I have written a QListModel based model to access data stored in a QMap. QMap is guaranteed to be sorted. So a conversion from QMap::iterator or const_iterator to int should be possible and sane.
At the moment I decrement the iterator and increment a counter variable:
QVariantMap::iterator it = m_data.upperBound(name); //or any other iterator
int pos = 0;
for (;it != m_data.begin();it--)
pos++;
//now pos contains the position of the entry at index in the map
For some data structures there is an int operator-(iterator)
defined it seems, allowing int pos = it - m_data.begin();
is there something similar for QMap?
Upvotes: 2
Views: 1679
Reputation: 238311
I'm not familiar with QMap in particular, but typically, that's the simplest algorithm to find the rank of an element in a map.
Assuming Qt iterators are usable with standard algorithms, you can simplify that to std::distance(m_data.begin(), it)
. Otherwise, you can implement distance
for QMap iterators yourself with the algorithm that you showed.
Upvotes: 3