获取QMap::iterator的位置(int)
Obtaining position (int) of a QMap::iterator
我编写了一个基于 QListModel 的模型来访问存储在 QMap 中的数据。 QMap 保证被排序。因此,从 QMap::iterator 或 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
。
我编写了一个基于 QListModel 的模型来访问存储在 QMap 中的数据。 QMap 保证被排序。因此,从 QMap::iterator 或 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
。