3
我想和接口的功能是这样的:查找迭代器的指数在STL容器 - 需要模板函数
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参数,但它看起来不那么好。会感谢优雅的解决方案。