Go back to Richel Bilderbeek's homepage.
Go back to Richel Bilderbeek's C++ page.
The Iterator is a Design Pattern to
'provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation' [1]
Example: IntVectorIterator
Technical facts
Application type(s)
Operating system(s) or programming environment(s)
IDE(s):
Project type:
C++ standard:
Compiler(s):
Libraries used:
STL: GNU ISO C++ Library, version 4.5.2
#-------------------------------------------------
#
# Project created by QtCreator 2011-06-01T06:16:13
#
#-------------------------------------------------
QT += core
QT -= gui
TARGET = CppDesignPatternIterator
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp \
intvectoriterator.cpp
HEADERS += \
intvectoriterator.h
|
intvectoriterator.cpp
//---------------------------------------------------------------------------
#include <cassert>
//---------------------------------------------------------------------------
#include "intvectoriterator.h"
//---------------------------------------------------------------------------
///IntVectorIterator is initialized by ranges
IntVectorIterator::IntVectorIterator(const std::vector<IntRange>& ranges)
: m_ranges(ranges)
{
First();
}
//---------------------------------------------------------------------------
///Set the IntVectorIterator back to the first element.
void IntVectorIterator::First()
{
m_current_range = m_ranges.begin();
m_current_int = m_current_range->first;
}
//---------------------------------------------------------------------------
///Go to the next element.
void IntVectorIterator::Next()
{
assert(!IsDone());
++m_current_int;
if (m_current_int == m_current_range->second)
{
++m_current_range;
if (m_current_range != m_ranges.end())
{
m_current_int = m_current_range->first;
}
}
}
//---------------------------------------------------------------------------
///Check if there are still elements left to iterator over.
bool IntVectorIterator::IsDone() const
{
return m_current_range == m_ranges.end();
}
//---------------------------------------------------------------------------
///Get the current item
std::vector<int>::iterator IntVectorIterator::CurrentItem() const
{
return m_current_int;
}
//---------------------------------------------------------------------------
|
intvectoriterator.h
main.cpp
- Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides. Design Patterns. 1995. ISBN: 0201633612.
Go back to Richel Bilderbeek's C++ page.
Go back to Richel Bilderbeek's homepage.
