在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);
据我所知,有 find()
在STL中返回迭代器。我需要返回迭代器的索引(即使对于非索引容器,如 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指数;
返回-1;
$ / code>
但编译器在 it
- 似乎不允许从模板化类型名称中获取 const_iterator
。我可以绕过吗?
在最坏的情况下,我可以传递开始和结束迭代器find_index参数,但它看起来不那么好。感谢优雅的解决方案。
解决方案
for(typename T :: const_iterator it = list.begin(); it!= list.end(); ++ it,++ index)
<当使用依赖类型(取决于模板参数的类型)时,编译器不知道 const_iterator $
typename
关键字,告诉他在C ++ 11中,还可以使用 auto
关键字绕过整个 typename
问题。
for(auto it = list.begin(); it!= list.end(); ++ it ++ index)
如果您已经有了迭代器从另一个操作开始),你也可以计算从列表的开始到这个迭代器的距离:
$ b $ $ $ $ $ $ $ $ #include< iterator> ;
int index = std :: distance(list.begin(),it);
但是由于这对 std :: list
,使用自制的 find_index
函数比 std :: find
后面跟着 std :: distance
,至少在表现方面。
I want to have a function with interface like this:
template<typename T, typename R> int find_index (const T& list, const R& value);
As I know, there is find()
in STL that returns iterator. I need to return index of iterator (even for non-indexed containers such as std::list
). I tried this code:
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;
}
But compiler shows error on it
- seems like it is not allowed to get const_iterator
from templated typename. Can I go around it?
At the worst case I can pass begin and end iterators to find_index arguments, but it looks not so fine. Would be thankful for elegant solution.
for (typename T::const_iterator it = list.begin(); it != list.end(); ++it, ++index)
should solve your problem.
When using dependent types (types depending on template parameters), the compiler does not know that const_iterator
is a type until it instantiates the template with a concrete type, it could also just be a static variable or whatever. Using the typename
keyword, you tell him that const_iterator
is really a type.
In C++11 you can also circumvent the whole typename
issue using the auto
keyword:
for (auto it = list.begin(); it != list.end(); ++it, ++index)
If you already have the iterator (maybe from some other operation), you can also just compute the distance from the list's begin to this iterator:
#include <iterator>
int index = std::distance(list.begin(), it);
But since this has linear complexity for a std::list
, using your self-made find_index
function is a better idea than std::find
followed by std::distance
, at least performance-wise.
这篇关于在STL容器中查找迭代器索引 - 需要模板功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!