首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::iterator

Defined in header <iterator>

?

?

template< class Category, class T, class Distance = std::ptrdiff_t, class Pointer = T*, class Reference = T& > struct iterator;

?

(deprecated in C++17)

std::iterator为简化迭代器所需类型的定义而提供的基类。

模板参数

Category

-

the category of the iterator. Must be one of iterator category tags.

T

-

the type of the values that can be obtained by dereferencing the iterator. This type should be void for output iterators.

Distance

-

a type that can be used to identify distance between iterators

Pointer

-

defines a pointer to the type iterated over (T)

Reference

-

defines a reference to the type iterated over (T)

成员类型

Member type

Definition

iterator_category

Category

value_type

T

difference_type

Distance

pointer

Pointer

reference

Reference

下面的示例演示如何实现输入迭代器通过从std::iterator继承。

二次

代码语言:javascript
复制
#include <iostream>
#include <algorithm>
 
template<long FROM, long TO>
class Range {
public:
    // member typedefs provided through inheriting from std::iterator
    class iterator: public std::iterator<
                        std::input_iterator_tag,   // iterator_category
                        long,                      // value_type
                        long,                      // difference_type
                        const long*,               // pointer
                        long                       // reference
                                      >{
        long num = FROM;
    public:
        explicit iterator(long _num = 0) : num(_num) {}
        iterator& operator++() {num = TO >= FROM ? num + 1: num - 1; return *this;}
        iterator operator++(int) {iterator retval = *this; ++(*this); return retval;}
        bool operator==(iterator other) const {return num == other.num;}
        bool operator!=(iterator other) const {return !(*this == other);}
        reference operator*() const {return num;}
    };
    iterator begin() {return iterator(FROM);}
    iterator end() {return iterator(TO >= FROM? TO+1 : TO-1);}
};
 
int main() {
    // std::find requires a input iterator
    auto range = Range<15, 25>();
    auto itr = std::find(range.begin(), range.end(), 18);
    std::cout << *itr << '\n'; // 18
 
    // Range::iterator also satisfies range-based for requirements
    for(long l : Range<3, 5>()) {
        std::cout << l << ' '; // 3 4 5
    }
    std::cout << '\n';
}

二次

产出:

二次

代码语言:javascript
复制
18
3 4 5

二次

另见

iterator_traits

provides uniform interface to the properties of an iterator (class template)

input_iterator_tagoutput_iterator_tagforward_iterator_tagbidirectional_iterator_tagrandom_access_iterator_tag

empty class types used to indicate iterator categories (class)

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com