C++ Iterator Library - <iterator>
Description
It is an iterator base class.
Declaration
Following is the declaration for std::iterator.
C++11
template <class Category,
class T,
class Distance = ptrdiff_t,
class Pointer = T*,
class Reference = T&>
class iterator;
Parameters
T − It indicates about type of element.
Distance − It represents the difference between two iterators.
Pointer − It represents a pointer to an element pointed by the iterator.
Reference − It represents a reference to an element pointed by the iterator.
Return value
none
Exceptions
If x somehow throws while applying the unary operator& to it, this function never throws exceptions.
Time complexity
constant for random-access iterators.
Example
The following example shows the usage of std::iterator.
#include <iostream>
#include <iterator>
class MyIterator : public std::iterator<std::input_iterator_tag, int> {
int* p;
public:
MyIterator(int* x) :p(x) {}
MyIterator(const MyIterator& mit) : p(mit.p) {}
MyIterator& operator++() {++p;return *this;}
MyIterator operator++(int) {MyIterator tmp(*this); operator++(); return tmp;}
bool operator==(const MyIterator& rhs) {return p==rhs.p;}
bool operator!=(const MyIterator& rhs) {return p!=rhs.p;}
int& operator*() {return *p;}
};
int main () {
int numbers[] = {1,2,3,4,5};
MyIterator from(numbers);
MyIterator until(numbers+5);
for (MyIterator it = from; it!=until; it++)
std::cout << *it << ' ';
std::cout << '\n';
return 0;
}
Let us compile and run the above program, this will produce the following result −
1 2 3 4 5
iterator.htm