【问题标题】:How to get index of bidirectional iterator with std::map?如何使用 std::map 获取双向迭代器的索引?
【发布时间】:2013-06-22 19:19:00
【问题描述】:

What is the most effective way to get the index of an iterator of an std::vector? 解释了如何为std::vectorstd::list 执行此操作,但是std::map 呢?

【问题讨论】:

    标签: c++ map stl iterator


    【解决方案1】:

    最简洁的方法是使用std::distance 函数:

    auto index = std::distance(myMap.begin(), myMapItr);
    

    但是,这在 O(n) 时间内运行,这对于大型地图来说效率很低。

    如果您需要确定迭代器在映射或其他有序集合中的索引,您可能需要搜索包含 order statistic tree 的库,这是一种支持高效 (O(1)或 O(log n)) 时间查找树中特定值的索引。

    或者,如果您在树上手动迭代,您可以在迭代器旁边放置一个计数器,每次从一个元素遍历到下一个元素时,您都会递增该计数器。这给出了迭代器索引的 O(1) 时间查找,但并不完全通用。

    希望这会有所帮助!

    【讨论】:

    • 这就是我喜欢这个网站的原因。
    【解决方案2】:

    试试这个:

    int IndexOf(Type *t)
    {
        Type** data = vector.data();
    
        int index = 0;
    
        while(*data++ != t)
        {
            index ++;
        }
    
        return index ;
    }
    

    【讨论】:

    • -1 因为这会获取向量中 的索引,而不是地图中迭代器(位置)的等效索引。
    猜你喜欢
    • 2010-10-14
    • 2010-09-13
    • 2014-11-10
    • 2011-02-06
    • 2012-08-28
    • 1970-01-01
    • 2014-09-19
    • 2014-04-24
    • 2011-06-03
    相关资源
    最近更新 更多