두 개의 반복자가 동일한 연산을 지원한다면, 그 두 연산의 이름은 같다.
입력 반복자(input iterator)
순차적 읽기 전용 접근
.==()
.!=()
.++()
.*() // 읽기
.->()
#include <iterator>
vector<int> v;
copy(istream_iterator<int>(cin), istream_iterator<int>(), back_inserter(v));
출력 반복자(output iterator)
순차적 쓰기 전용 접근
write-once ( single-assignment )
++()
.*() // 쓰기
std::back_inserter
#include <iterator>
...
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
순방향 반복자(forward iterator)
순차적 읽기-쓰기 접근
std::binary_search()
양방향 반복자(bidirectional iterator)
.--()
임의 접근 반복자 // 인덱스?
p + n, p - n, 및 n + p
p - q
p[n] or *(p + n)
p < q, p > q, p <= q, 및 p >= q
std:: sort()
std::vector<>
std::string
#include <exception>
class iterator_overflow : public exception {
public:
iterator_overflow( int index, int max )
: _index( index ), _max( max )
{}
int index() { return _index; }
int max() { return _max; }
const char* what() const;
private:
int _index;
int _max;
};
const char *
iterator_overflow::
what() const
{
...
}
class Triangular_iterator
{
public:
Triangular_iterator( int index ) : _index( index-1 ){}
bool operator==( const Triangular_iterator& ) const;
bool operator!=( const Triangular_iterator& ) const;
int operator*() const;
int operator++(); // prefix
int operator++( int ); // postfix
private:
void check_integrity() const;
int _index;
};
inline void Triangular_iterator::
check_integrity() const
{
if ( _index >= Triangular::_max_elems )
throw iterator_overflow()
...
}
inline bool Triangular_iterator::
operator==( const Triangular_iterator &rhs ) const
{ return _index == rhs._index; }
inline bool Triangular_iterator::
operator!=( const Triangular_iterator &rhs ) const
{ return !( *this == rhs._index ); }
inline int Triangular_iterator::
operator*() const
{
check_integrity();
return Triangular_iterator::_elems[ _index ];
}
or
inline int
operator*( const Triangular_iterator:: &rhs )
{
rhs.check_integrity();
return Triangular_iterator::_elems[ rhs.index() ];
}
inline int& Triangular_iterator::
operator++()
{
++_index;
check_integrity();
return Triangular_iterator::_elems[ _index ];
}
inline int& Triangular_iterator::
operator++( int )
{
check_integrity();
return Triangular_iterator::_elems[ _index++ ];
}
#include "Triangular_iterator.h"
class Triangular {
typedef Triangular_iterator iterator;
Triangular_iterator begin() const
{
return Triangular_iterator( _beg_pos );
}
Triangular_iterator end() const
{
return Triangular_iterator( _beg_pos+_length );
}
...
private:
int _beg_pos;
int _length;
...
};