正在获取QMap::迭代器的位置(int)

Obtaining position (int) of a QMap::iterator

本文关键字:位置 int 迭代器 获取 QMap      更新时间:2023-10-16

我已经编写了一个基于QListModel的模型来访问存储在QMap中的数据。QMap是有排序保证的。因此,从QMap::迭代器或const_iterator到int的转换应该是可能的并且合理的。

此刻,我递减迭代器并递增一个计数器变量:

    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

对于某些数据结构,似乎定义了int operator-(iterator),允许int pos = it - m_data.begin();,QMap是否也有类似的内容?

我对QMap并不特别熟悉,但通常情况下,这是查找映射中元素秩的最简单算法。

假设Qt迭代器可用于标准算法,则可以将其简化为std::distance(m_data.begin(), it)。否则,您可以使用所展示的算法为QMap迭代器自己实现distance