如何检查传递的迭代器是随机访问迭代器?

How to check that the passed Iterator is a random access iterator?(如何检查传递的迭代器是随机访问迭代器?)
本文介绍了如何检查传递的迭代器是随机访问迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);
  // ...
}

(last - first) 表达式 (AFAIK) 仅适用于随机访问迭代器(例如来自 vectordeque 的迭代器).如何检查传递的迭代器满足此要求的代码?

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?

推荐答案

如果Iterator是随机访问迭代器,那么<​​/p>

If Iterator is a random access iterator, then

std::iterator_traits<Iterator>::iterator_category

将是 std::random_access_iterator_tag.实现这一点的最简洁方法可能是创建第二个函数模板并让 Foo 调用它:

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());
}

这样做的好处是您可以根据需要为不同类别的迭代器重载 FooImpl.

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

Scott Meyers 在一本Effective C++ 书中讨论了这种技术(我不记得是哪一本了).

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)