【发布时间】:2013-06-22 19:19:00
【问题描述】:
What is the most effective way to get the index of an iterator of an std::vector? 解释了如何为std::vector 或std::list 执行此操作,但是std::map 呢?
【问题讨论】:
What is the most effective way to get the index of an iterator of an std::vector? 解释了如何为std::vector 或std::list 执行此操作,但是std::map 呢?
【问题讨论】:
最简洁的方法是使用std::distance 函数:
auto index = std::distance(myMap.begin(), myMapItr);
但是,这在 O(n) 时间内运行,这对于大型地图来说效率很低。
如果您需要确定迭代器在映射或其他有序集合中的索引,您可能需要搜索包含 order statistic tree 的库,这是一种支持高效 (O(1)或 O(log n)) 时间查找树中特定值的索引。
或者,如果您在树上手动迭代,您可以在迭代器旁边放置一个计数器,每次从一个元素遍历到下一个元素时,您都会递增该计数器。这给出了迭代器索引的 O(1) 时间查找,但并不完全通用。
希望这会有所帮助!
【讨论】:
试试这个:
int IndexOf(Type *t)
{
Type** data = vector.data();
int index = 0;
while(*data++ != t)
{
index ++;
}
return index ;
}
【讨论】: