std::iterator
From cppreference.com
| 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 is the base class provided to simplify definitions of the required types for iterators.
Template parameters
| 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 types
| Member type | Definition |
iterator_category
|
Category
|
value_type
|
T
|
difference_type
|
Distance
|
pointer
|
Pointer
|
reference
|
Reference
|
Example
The following example shows how to implement iterator traits by inheriting from std::iterator
Run this code
#include <iostream>
#include <algorithm>
template<long FROM, long TO>
class Range {
public:
// iterator traits provided through inheriting from std::iterator
// and providing template parameters in the right order
class iterator: public std::iterator<
std::forward_iterator_tag, // iterator_category
long, // value_type
long, // difference_type
long*, // pointer
long& // reference
>{
long num = FROM;
public:
iterator(long _num = 0) : num(_num) {}
iterator operator++(){num = TO >= FROM ? num + 1: num - 1; return *this;}
bool operator!=(iterator other)const {return num != other.num;}
long operator*() {return num;}
};
iterator begin() {return FROM;}
iterator end() {return TO >= FROM? TO+1 : TO-1;}
};
int main() {
// range-based-for works even if iterator doesn't provide valid traits
for(long l : Range<3, 5>()) {
std::cout << l << ' '; // 3 4 5
}
std::cout << std::endl;
// std::find requires iterator to provide valid traits
auto range = Range<15, 25>();
auto itr = std::find(range.begin(), range.end(), 18);
std::cout << *itr << std::endl; // 18
}
Output:
3 4 5
18
See also
| provides uniform interface to the properties of an iterator (class template) | |
| empty class types used to indicate iterator categories (class) |