简体   繁体   English

指针或类作为迭代器?

[英]Pointer or class as iterator?

I'm writing a random access container in C++. 我正在用C ++编写随机访问容器。 In my code I use this (well, in my real code I use all kinds of Allocator typedefs, this is just easier to understand): 在我的代码中我使用它(好吧,在我的实际代码中我使用各种Allocator typedef,这更容易理解):

template<typename T, typename Allocator = std::allocator<T> >
class Carray {
public:
    // ...
    typedef T* iterator;
    typedef const T* const_iterator;
    // ...
};

But I can also create a different iterator class derived from std::iterator . 但我也可以创建一个从std::iterator派生的不同迭代器类。 This would add support for typedefs ( it::iterator_category , it::difference_type , etc). 这将添加对typedef的支持( it::iterator_categoryit::difference_type等)。

Now my question, is there an overhead by using a iterator class instead of a raw pointer? 现在我的问题是,使用迭代器类而不是原始指针是否存在开销? If yes, how substantial is this overhead, and is it severe enough to not use a iterator class? 如果是,这个开销有多大,并且它是否严重到不使用迭代器类?

You have iterator category, difference type etc avalaibale for you even if you have a raw pointer. 即使你有一个原始指针,你也有你的迭代器类别,差异类型等avalaibale。 You see, there is this iterator_traits<> template which you should use. 你看,你应该使用这个iterator_traits<>模板。 It is already specialized for pointers. 它已经专门用于指针。

iterator_traits<int*>::value_type // ... etc. 
//or
iterator traits<my_custom_iterator>::value_type

If your iterator class simply wraps the pointer, there is almost certainly no overhead. 如果您的迭代器类只是包装指针,几乎肯定没有开销。

It's perfectly standard-conforming to use raw pointers as the iterators. 它完全符合标准 - 使用原始指针作为迭代器。 However, some badly written code (including, as you suggest, code that tries to use nested typedefs directly instead of iterator_traits) may fail to compile. 但是,一些编写错误的代码(包括,如您所建议的那样,尝试直接使用嵌套typedef而不是iterator_traits的代码)可能无法编译。 Some of the early standard libraries started with pointers for vector's iterators and changed, purely to keep such bad code working. 一些早期的标准库以向量迭代器的指针开始并进行了更改,纯粹是为了防止这些糟糕的代码工作。 That's really the only reason I'd think of for bothering. 这才是我想到打扰的唯一原因。

BTW - if possible I'd make use of the Boost iterator support rather than deriving directly from std::iterator; BTW - 如果可能的话,我会使用Boost迭代器支持,而不是直接从std :: iterator派生; a lot of subtle requirements are taken care of for you that way. 很多细微的要求都是以这种方式照顾你的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM