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

标签 c++ list templates stl find

我想要一个界面如下的函数:

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,至少在性能方面是这样。

关于c++ - 在 STL 容器中查找迭代器的索引 - 需要模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7930887/

相关文章:

java - 在 Velocity 模板中按名称引用 map

c++ - waitpid 似乎没有进食

python - 如何使用 dict 值列表将字典列表转换为 dict

c++ - 内存分配练习

java - 在 fxml 中显示整个链表

Python - 我只能通过 append 保存一件事?

c++ - 类方法的 SFINAE

angular - 作为 Angular2 组件的 Typescript 泛型类

c++ - 如何制作嵌套聚合初始化器?

c++ - 将 Linux 32 位应用程序移植到 64 位?