繁体   English   中英

在STL容器中查找迭代器的索引 - 需要模板函数

[英]Find index of iterator in STL container - need template function

我希望有一个像这样的接口函数:

template<typename T, typename R> int find_index (const T& list, const R& value);

据我所知,STL中有find()返回迭代器。 我需要返回迭代器的索引(即使对于非索引容器,例如std::list )。 我试过这段代码:

template<typename T, typename R>
int find_index (const T& list, const R& value)
{
    int index = 0;
    for (T::const_iterator it = list.begin(); it != list.end(); it++, index++)
        if ((*it) == value)
            return index;
    return -1;
}

但是编译器显示出错it -好像它是不允许获得const_iterator从模板类型名称。 我可以到处走走吗?

在最坏的情况下,我可以将开始和结束迭代器传递给find_index参数,但它看起来不太好。 会感谢优雅的解决方案。

for (typename T::const_iterator it = list.begin(); it != list.end(); ++it, ++index)

应该解决你的问题。

当使用依赖类型(类型取决于模板参数)时,编译器不知道const_iterator是一个类型,直到它用具体类型实例化模板,它也可能只是一个静态变量或其他。 使用typename关键字,告诉他const_iterator实际上是一个类型。

在C ++ 11中,您还可以使用auto关键字规避整个typename问题:

for (auto it = list.begin(); it != list.end(); ++it, ++index)

如果你已经有了迭代器(可能来自其他一些操作),你也可以计算从列表的开始到这个迭代器的距离:

#include <iterator>

int index = std::distance(list.begin(), it);

但由于这对于std::list具有线性复杂性,因此使用自制的find_index函数比std::find后跟std::distance更好,至少在性能方面。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM