如何检查传递的迭代器是一个随机访问迭代器? [英] How to check that the passed Iterator is a random access iterator?

查看:94
本文介绍了如何检查传递的迭代器是一个随机访问迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,它执行一些迭代器算术:

  template< class Iterator> 
void Foo(Iterator first,Iterator last){
typedef typename Iterator :: value_type Value;
std :: vector< Value> vec;
vec.resize(last - first);
// ...
}

(例如向量 deque c)的表达式(最后一个) / code>)。如果迭代器

解决方案

code>是随机存取迭代器,然后

  std :: iterator_traits< Iterator> :: iterator_category 

将会是 std :: random_access_iterator_tag 。实现这个的最简单的方法可能是创建第二个函数模板,并且 Foo 调用它:

  template< typename Iterator> 
void FooImpl(Iterator first,Iterator last,std :: random_access_iterator_tag){
// ...
}

template< typename Iterator>
void Foo(Iterator first,Iterator last){
typedef typename std :: iterator_traits< Iterator> :: iterator_category category;
return FooImpl(first,last,category());
}

这样做的好处是可以重载 FooImpl

Scott Meyers在有效的C ++ 之一中讨论了这种技术。书(我不记得哪一个)。


I have the following code, which does some iterator arithmetic:

template<class Iterator>
void Foo(Iterator first, Iterator last) {
  typedef typename Iterator::value_type Value;
  std::vector<Value> vec;
  vec.resize(last - first);
  // ...
}

The (last - first) expression works (AFAIK) only for random access iterators (like the ones from vector and deque). How can I check in the code that the passed iterator meets this requirement?

解决方案

If Iterator is a random access iterator, then

std::iterator_traits<Iterator>::iterator_category

will be std::random_access_iterator_tag. The cleanest way to implement this is probably to create a second function template and have Foo call it:

template <typename Iterator>
void FooImpl(Iterator first, Iterator last, std::random_access_iterator_tag) { 
    // ...
}

template <typename Iterator>
void Foo(Iterator first, Iterator last) {
    typedef typename std::iterator_traits<Iterator>::iterator_category category;
    return FooImpl(first, last, category());
}

This has the advantage that you can overload FooImpl for different categories of iterators if you'd like.

Scott Meyers discusses this technique in one of the Effective C++ books (I don't remember which one).

这篇关于如何检查传递的迭代器是一个随机访问迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆